问题描述
我正在尝试更新 Java 程序以支持非常大的输出。目前程序支持长型数据,我想把长型改成BigInteger类。
这是原来的程序,
class WaysDP_long
{
static int A = 3;
static int B = 2;
static int C = 2;
static long CountWays(int a,int b,int c,long [][][]dp)
{
if (a > A || c >= C) return 0L;
if (b >= B) return 1L;
if (dp[a][b][c] != -1) return dp[a][b][c];
long ways = 0;
ways += CountWays(a+1,b,c+1,dp);
ways += CountWays(a+1,b+1,c,b+2,b+4,dp);
// Memorize and return
return dp[a][b][c] = ways;
}
// Driver code
public static void main(String[] args)
{
long[][][] dp = new long[A+1][B+5][C];
for(int i = 0; i < A+1; i++)
for(int j = 0; j < B+5; j++)
for(int k = 0; k < C; k++) dp[i][j][k]=-1L;
System.out.println(CountWays(0,dp));
}
}
为了支持更大的 A、B 和 C 值,我试图将一些变量转换为 BigInteger, 这是我更新的代码,
class WaysDP_Large
{
static int A = 3;
static int B = 2;
static int C = 2;
static boolean[][][] supportDP = new boolean[B+1][A+5][C]; // to avoid BigInteger negative initialization.
static BigInteger CountWays(int a,BigInteger [][][]dp)
{
if (a > B || c >= C) return BigInteger.ZERO;
if (b >= A) return BigInteger.ONE;
if (supportDP[a][b][c]) return dp[a][b][c];
BigInteger ways = BigInteger.ZERO;
ways.add(CountWays(a+1,dp));
ways.add(CountWays(a+1,dp));
// Memorize and return
supportDP[a][b][c] = true;
//dp[ballsPlayed][currentscore][wicketsGone] = new BigInteger();
return dp[a][b][c] = ways;
}
// Driver code
public static void main(String[] args)
{
BigInteger[][][] dp = new BigInteger[B+1][A+5][C];
for(int i = 0; i < B+1; i++)
for(int j = 0; j < A+5; j++)
for(int k = 0; k < C; k++) supportDP[i][j][k] = false;
// for(int i = 0; i < balls+1; i++)
// for(int j = 0; j < target+5; j++)
// for(int k = 0; k < wickets; k++) dp[i][j][k] = BigInteger.ZERO;
System.out.println(CountWays(0,dp));
}
}
但更新后的代码总是给出输出 0,它应该给出 13。 [对于 3、4、3,它将是 20]
可能是 BigInteger 赋值和添加的问题。任何克服问题的提示将不胜感激。谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)