Nearest Sequence
Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 374 Solved: 120
[ Submit][ Status][ Web Board]
Description
Do you remember the "Nearest Numbers"? Now here comes its brother:"Nearest Sequence".Given three sequences of char,tell me the length of the longest common subsequence of the three sequences.
Input
There are several test cases.For each test case,the first line gives you the first sequence,the second line gives you the second one and the third line gives you the third one.(the max length of each sequence is 100)
Output
For each test case,print only one integer :the length of the longest common subsequence of the three sequences.
Sample Input
abcd
abdc
dbca
abcd
cabd
tsc
Sample Output
2
1
解决方案:由两串的最大公共子串的公式:dp[i][j]=max(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]);当遇到三个串的时候,随便搞搞就行了。
code:#include<iostream> #include<cstdio> #include<cstring> using namespace std; int dp[102][102][102]; char str[102],str1[102],str2[102]; int main() { str[0]=str1[0]=str2[0]='#'; while(~scanf("%s",str+1)) { // getchar(); scanf("%s",str1+1); // getchar(); scanf("%s",str2+1); // getchar(); int len=strlen(str); int len1=strlen(str1); int len2=strlen(str2); // cout<<len<<len1<<len2<<endl; int MAx=0; for(int i=1; i<len; i++) { for(int j=1; j<len1; j++) { for(int k=1; k<len2; k++) { if(str[i]==str1[j]&&str1[j]==str2[k]){ int a=max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); int b=max(dp[i-1][j-1][k],max(dp[i][j-1][k-1],dp[i-1][j][k-1])); int c=max(a,b); dp[i][j][k]=max(c,dp[i-1][j-1][k-1]+1); } else{ int a=max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); int b=max(dp[i-1][j-1][k],max(dp[i][j-1][k-1],dp[i-1][j][k-1])); int c=max(a,b); dp[i][j][k]=c; } if(dp[i][j][k]>MAx)MAx=dp[i][j][k]; } } } printf("%d\n",MAx); } return 0; }