csuoj1060: Nearest Sequence 动态规划

来源:互联网 发布:神圣罗马帝国历史 知乎 编辑:程序博客网 时间:2024/05/21 17:03

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

abcdabdcdbcaabcdcabdtsc

Sample Output

21

用dp开个三维数组,如果难以理解的话可以先做poj1458Common Subsequence这道题,它只要比较两个字符串  http://poj.org/problem?id=1458
我的这个代码还可以优化,不过A了就没管了,三个循环一个一个比过去就OK的。
AC代码:
#include<iostream>#include<cstring>using namespace std;char s1[105],s2[105],s3[105];int dp[105][105][105];int ans;void DP(){  memset(dp,0,sizeof dp);  int n1=strlen(s1);  int n2=strlen(s2);  int n3=strlen(s3);  for(int i=1;i<=n1;i++)  for(int j=1;j<=n2;j++)  for(int k=1;k<=n3;k++)  {    if(s1[i-1]==s2[j-1]&&s2[j-1]==s3[k-1])    dp[i][j][k]=dp[i-1][j-1][k-1]+1;    else    dp[i][j][k]=max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1]));  }  ans=dp[n1][n2][n3];}int main(){  while(cin>>s1>>s2>>s3)  {    DP();    cout<<ans<<endl;  }  return 0;}



原创粉丝点击