算法导论动态规划小结: 找出最有子结构,其次证明问题具有最有子结构,最后总结出状态转移方程,分析边界情况。 #include<iostream> using namespace std; //矩阵相乘 O(n^3) int sum = 0; int a[100][100] = {0}; int b[100][100] = {0}; int c[100][100] = {0}; int MatrixMulti(int m,int n,int l)//矩阵相乘 { // a[1][i]*b[i][1] = c[1][1] (1<=i<=n) // a[2][k]*b[k][4] = c[2][4] (1<=k<=n) // a[i][k]*b[k][j] = c[i][j] int i,j,k; for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { for(k=1;k<=l;k++) { c[i][j] = a[i][k]*b[k][j]; sum += a[i][k]*b[k][j]; } } } return sum; } //矩阵链相乘的迭代算法 int p[100] = {0};//矩阵的值 int m[100][100] = {0}; int s[100][100] = {0}; void MatrixChain(int *p,int **m,int n) { int i,j,k,r; for(i=0; i<=n; i++) m[i][i] = 0; for(r=2; r<=n; r++) { for(i=1; i<=n-r+1; i++) { j = i + r - 1; m[i][j] = m[i+1][j] + p[i-1]*p[i]*p[j]; s[i][j] = i; for(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; } } } } } //输出解得路径 void ans(int i,int j) { if(j==i) cout << 0; else { int k = m[i][j]; cout << i << "->" << j << "is" << k << endl; if(j-i>1) { ans(i,k); ans(k+1,j); } } } //递归方案 void GetSum() { int i,j; for(i=0;i<=n;i++) { for(j=0;j<=n;j++) m[i][j] = 0; } RecurMatrix(1,n); } int RecurMatrix(int i,int j) { if(m[i][j] > 0)//做备忘录 return m[i][j]; if(i == j) return 0; int u = RecurMatrix(i,i) + RecurMatrix(i+1,j) + p[i-1]*p[i]*p[j];//形成递归树的过程 s[i][j] = i; for(int k=i+1;k<j;k++) { int t = RecurMatrix(i,k) + RecurMatrix(k+1,j) + p[i-1]*p[k]*p[j];//形成递归树的过程,参考原书54页 if(t < u) { u = t; s[i][j] = k; } } return u; } 理解递归树 (1 - 4) (1-1) (2-3) (1,2) (3,4) (1-3) (4-4) / //最长公共子序列longest common sequence int m[100][100] = {0}; char a[100]; char b[100]; int ans[100] = {0}; int LCS(char *a,char *b,int m,int n) { int i,j,k=1; //memset(m,100*100,sizeof(int)); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { if(a[i]==b[j]) { m[i][j] = m[i-1][j-1]+1; ans[k++] = i; } else if(m[i-1][j]<m[i][j-1]) { m[i][j] = m[i][j-1]; } else { m[i][j] = m[i-1][j]; } } } } void getAns(int *ans,int k) { for(int i=1;i<k;i++) { cout << a[ans[i]] << "-> "; } } ///