最长公共子序列(LCS)问题,dp解决。
要注意每次输出结果后要空行!!!题目的例子上居然没空,害我WA了两次才找到原因 =--=
解题代码如下:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define maxn 105 int Tower1[maxn], Tower2[maxn]; int N1, N2; int LongLen[maxn][maxn]; int dp(int i, int j) { if(!i || !j) return 0; if(LongLen[i][j]>=0) return LongLen[i][j]; if(Tower1[i]==Tower2[j]) return LongLen[i][j] = dp(i-1,j-1)+1; else return LongLen[i][j] = max( dp(i-1,j), dp(i,j-1)); } int main() { int Case = 0; while(cin >> N1 >> N2 && N1 && N2) { for(int i=1; i<=N1; i++) cin >> Tower1[i]; for(int i=1; i<=N2; i++) cin >> Tower2[i]; memset(LongLen,-1,sizeof(LongLen)); printf("Twin Towers #%d Number of Tiles : %d ", ++Case, dp(N1,N2)); } return 0; }