Common Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 21529 Accepted Submission(s): 9351
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int dp[1000][1000];//dp[i][j]表示由s1的前i位與s2的前j位所得到的最長公共子序列長度(注意dp從1開始,字符串下標從0開始)
int main()
{
char s1[1000],s2[1000];
while(scanf("%s%s",s1,s2)!=EOF)
{
memset(dp,0,sizeof(dp));
int i,j,lenth1=strlen(s1),lenth2=strlen(s2);
for(i=0;i<lenth1;i++)
{
for(j=0;j<lenth2;j++)
{
if(s1[i]==s2[j])//若s1的第i(從0開始)位與s2的第j位相匹配。
dp[i+1][j+1]=dp[i][j]+1;//則s1的前i位與s2的前j位所得到的最長公共子序列長度=s1的前i-1位與s2的前j-1位所得到的最長公共子序列長度+1
else
dp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1]);//不匹配的話就有兩種情況,取最大值就可以了。
}
}
printf("%d\n",dp[lenth1][lenth2]);
}
return 0;
}
注意到:if(s1[i]==s2[j])
dp[當前行][j+1]=dp[上一行][j]+1;
else
dp[當前行][j+1]=max(dp[當前行][j],dp[上一行][j+1]);
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int dp[2][1000];//滾動數組,dp[0],dp[1]交替表示上一次,當前的dp。
int main()
{
char s1[1000],s2[1000];
while(scanf("%s%s",s1,s2)!=EOF)
{
memset(dp,0,sizeof(dp));
int i,j,lenth1=strlen(s1),lenth2=strlen(s2);
int e=0;
for(i=0;i<lenth1;i++)
{
e=1-e;//e是當前行
for(j=0;j<lenth2;j++)
{
if(s1[i]==s2[j])
dp[e][j+1]=dp[1-e][j]+1;//1-e是上一行
else
dp[e][j+1]=max(dp[e][j],dp[1-e][j+1]);
}
}
printf("%d\n",dp[e][lenth2]);
}
return 0;
}