【发布时间】:2017-04-17 05:42:02
【问题描述】:
据我所知,自底向上的复杂度应该是 n^3,但是,我告诉我它几乎像 O(n)。我已经多次检查这些代码,但仍然不知道为什么它不是 n^3 复杂性。我在这里想念什么吗?
/**
* Using the bottom-up approach to fill in the table m and s for matrices P
* @param P an array storing the matrices chain
*/
public void matrixChainOrder(int[] P){
int n = P.length-1;
m = new int[n+1][n+1];
s = new int[n][n+1];
for (int i=1; i <= n; i++ ){
m[i][i] = 0;
}
for (int l = 2; l <= n; l++){
for (int i = 1; i <= n-l + 1; i++){
int j = i + l - 1;
m[i][j] = Integer.MAX_VALUE;
for (int k = i; k <= j -1; k++){
int q = m[i][k] + m[k+1][j] + P[i-1]*P[k]*P[j];
if (q < m[i][j]){
m[i][j] = q;
s[i][j] = k;
}
}
}
}
}
/**
* Print out the optimal parenthesization of matrices chain P
* @param s the auxiliary table storing the parenthesization
* @param i the index of the start matrix
* @param j the index of the end matrix
*/
public void printOptimalParens(int[][] s, int i, int j){
if (i == j){
System.out.print("A"+ i);
}
else{
System.out.print("(");
printOptimalParens(s, i, s[i][j]);
printOptimalParens(s, s[i][j] + 1, j);
System.out.print(")");
}
}
/**
* Compute the product of the matrices chain
* @param A The matrices chain, it is an array of matrices
* @param s the auxiliary table storing the parenthesization
* @param i the start matrix
* @param j the end matrix
* @return the product matrix of the matrices chain
*/
public long[][] matrixChainMultiply(long[][][] A, int[][] s, int i, int j){
if (i == j){
return A[i];
}
if (i + 1 == j){
return multiply(A[i], A[j]);
}
long[][] C = matrixChainMultiply(A, s, i, s[i+1][j+1]-1);
long[][] D = matrixChainMultiply(A, s, s[i+1][j+1], j);
return multiply(C, D);
}
/**
* A helper method to compute 2 matrices
* @param X the first matrix
* @param Y the secodn matrix
* @return the product of these two matrices
*/
public long[][] multiply(long[][] X, long[][] Y){
int r = X.length;
int c = X[0].length;
int c2 = Y[0].length;
long[][] B = new long[r][c2];
for (int u = 0; u < r; u++){
for (int v = 0; v < c2; v++){
for (int w = 0; w < c; w++){
B[u][v] += X[u][w] * Y[w][v];
}
}
}
return B;
}
【问题讨论】:
-
我认为最好也解释一下为什么你认为你的算法是 O(n)。
-
我写了一个测试驱动,结果显示它几乎像 O(n)
-
你试过的n(链的长度?)的值是多少?
-
我累了 6 9 12 13 16 19 21 24。他们都给我看了
-
完成这个需要多长时间?如果它太快(不到 3 秒),那么它可能不可靠。你能试试 N=10 和 N=100 吗?
标签: algorithm sorting graph-algorithm