也是DP入门题,紫书第九章
这里讲得很清晰:
http://www.cnblogs.com/xudong-bupt/archive/2013/03/15/2959039.html
模板:
int n,m; char a[MAXN],b[MAXN],res[MAXN]; int dp[MAXN][MAXN],dir[MAXN][MAXN]; //dir 1斜上,2左,3上 void lcs(int al,int bl) { int i,j; for(i=1;i<=al;i++) { for(j=1;j<=bl;j++) { if(a[i-1] == b[j-1]) { dp[i][j] = dp[i-1][j-1]+1; dir[i][j] = 1; } else if(dp[i-1][j]>dp[i][j-1]) { dp[i][j] = dp[i-1][j]; dir[i][j] = 3; } else { dp[i][j] = dp[i][j-1]; dir[i][j] = 2; } } } } void getlcs(int al,int bl) { int i = al; int j = bl; int k = 0; while(i && j) { if(dir[i][j] == 1) { res[k++] = a[i-1]; i--;j--; } else if(dir[i][j]==2) j--; else if(dir[i][j]==3) i--; } for(int v = k-1;v>=0;v--) pf("%c",res[v]); }
时间: 2024-12-28 20:50:35