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

poj 1458 Common Subsequence(lcs模板)

2015-08-10 17:58 417 查看
Description
Asubsequenceofagivensequenceisthegivensequencewithsomeelements(possiblenone)leftout.GivenasequenceX=<x1,x2,...,xm>anothersequenceZ=<z1,z2,...,zk>isasubsequenceofXifthereexistsastrictly
increasingsequence<i1,i2,...,ik>ofindicesofXsuchthatforallj=1,2,...,k,xij=zj.Forexample,Z=<a,b,f,c>isasubsequenceofX=<a,b,c,f,b,c>withindexsequence<1,2,4,6>.GiventwosequencesX
andYtheproblemistofindthelengthofthemaximum-lengthcommonsubsequenceofXandY.

Input
Theprograminputisfromthestdinput.Eachdatasetintheinputcontainstwostringsrepresentingthegivensequences.Thesequencesareseparatedbyanynumberofwhitespaces.Theinputdataarecorrect.
Output
Foreachsetofdatatheprogramprintsonthestandardoutputthelengthofthemaximum-lengthcommonsubsequencefromthebeginningofaseparateline.

SampleInput
abcfbcabfcab
programmingcontest
abcdmnp

SampleOutput
4
2
0


#include<stdio.h>
#include<string.h>
chars1[1010],s2[1010];
intdp[1010][1010];//开一个dp数组用来存储最长子串的长度;
intmax(inta,intb)
{
if(a>b)
returna;
elsereturnb;
}
//#definemax(a,b)(a>b?a:b)这样比较两个数大小比较简单
intmain()
{
while(scanf("%s%s",&s1,&s2)!=EOF)
{
memset(dp,0,sizeof(dp));
intlen1=strlen(s1);
intlen2=strlen(s2);
inti,j;
for(i=1;i<=len1;i++)
{
for(j=1;j<=len2;j++)
{
if(s1[i-1]==s2[j-1])//如果最后一位字符一样就+1
{
dp[i][j]=dp[i-1][j-1]+1;
}
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);//不是的话就取最大的继续循环
}
}
printf("%d\n",dp[len1][len2]);
}
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: