您的位置:首页 > 产品设计 > UI/UE

pku 1458 Common Subsecquence(DP)

2009-07-15 22:47 423 查看
 

题目大意:给定两个字符串,求其最大的公共子串。在这里子串的定义是:Given a sequence X = < x1, x2, ..., xm > ,another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >.
分析:简单DP
if(first[i]=second[j]) //在最大公共子串中,first[i]和second[j]恰好配对
count[i][j]=count[i-1][j-1]+1;
else count[i][j]=max(count[i-1][j],count[i][j-1]); //否则
 
#include <iostream>
using namespace std;
#define Max(x,y) (x<y?y:x)
short count[1005][1005],first_n,second_n,k;
char first[1005],second[1005];
void DP();
int main()
{
while(scanf("%s",first+1)!=EOF)
{
scanf("%s",second+1);
first_n=strlen(first+1);
second_n=strlen(second+1);
DP();
printf("%hd/n",count[first_n][second_n]);
}
return 0;
}
void DP()
{
memset(count,0,sizeof(count));
for(int i=1;i<=first_n;i++)
for(int j=1;j<=second_n;j++)
if(first[i]==second[j]) count[i][j]=count[i-1][j-1]+1;
else count[i][j]=Max(count[i][j-1],count[i-1][j]);
}
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  zk c