题目来源:http://poj.org/problem?id=1458
题意:求最长公共子序列问题
思路:经典dp问题,用dp[i][j]表示串1的前i个和串2的前j个的最长公共子序列。则当s1[i]=s2[j]时,dp[i][j] = dp[i-1][j-1] + 1,否则,dp[i][j] = max(dp[i-1][j] , dp[i][j-1])
代码:
#include<iostream>
#include <string>
#include <string.h>
#include <cstdio>
using namespace std;
#define CLR(arr,val) memset(arr,val,sizeof(arr))
int dp[1005][1005];
int max(int a,int b){
return a>b?a:b;
}
int main(){
//freopen("1.txt","r",stdin);
//string s1,s2;
char s1[1005],s2[1005];
while(scanf("%s",s1+1) != EOF){
scanf("%s",s2+1);
int len1 = strlen(s1);
int len2 =strlen(s2);
CLR(dp,0);
for(int i = 1;i <= len1;++i){
for(int j = 1;j <= len2;++j){
if(s1[i] == s2[j]){
dp[i][j] = dp[i-1][j-1]+1;
//cout<<"ss"<<endl;
//printf("%c%c",s1[i],s2[j]);
}
else{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
printf("%d\n",dp[len1][len2]-1);
}
return 0;
}