1. 程式人生 > >多矩陣相乘的最優演算法

多矩陣相乘的最優演算法

public class BestNumber {

	public int[][] good(int[] p,int[][] m,int[][] s) {
		int n = p.length -1;
	    for(int r = 2;r<=n;r++) {
		for(int i = 1;i<=n-r+1;i++) {
			int j = i+r-1;
			m[i][j] = m[i+1][j] + p[i-1] * p[i] * p[j];
			s[i][j] = i;
			for(int k = i+1;k<j;k++) {
				int t = m[i][k] + m[k+1][j] + p[i-1] * p[k] * p[j];
				if(t<m[i][j]) {
					m[i][j]=t;
					s[i][j]=k;
				}
			}
		}
	}
	    return s;
	}
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("請輸入要輸入數字的個數:");
		int number = input.nextInt();
		int[] p = new int[number];
		for(int i = 0;i<p.length;i++) {
			p[i] = input.nextInt();
		}
		System.out.println("p陣列已經 完畢");
		BestNumber best = new BestNumber();
		int[][] m = new int[number][number];
		int[][] s = new int[number][number];
		best.good(p,m,s);
		for(int x = 1;x<number;x++) {
			for(int y = 1;y<number;y++) {
				System.out.println(s[x][y]);
			}
		}
	}
}