http://acm.hdu.edu.cn/showproblem.php?pid=1503
最长公共子序列 用个p[i][j]记录dp[i][j]是从哪个位置传递过来的
然后dfs输出,基本都是看的别人题解,然后自己写的,就不多说了
代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
using namespace std;
char word1[105];
char word2[105];
int dp[105][105];
int p[105][105];
int dfsprint(int n,int m)
{
//printf("%d %d\n",n,m);
if(n==0&&m==0)
return 1;
else if(n==0&&m!=0)
{
dfsprint(n,m-1);
printf("%c",word2[m]);
}
else if(n!=0&&m==0)
{
dfsprint(n-1,m);
printf("%c",word1[n]);
}
else if(p[n][m]==1)
{
dfsprint(n-1,m-1);
printf("%c",word1[n]);
}
else if(p[n][m]==2)
{
dfsprint(n,m-1);
printf("%c",word2[m]);
}
else
{
dfsprint(n-1,m);
printf("%c",word1[n]);
}
}
int main()
{
while(scanf("%s%s",word1+1,word2+1)==2)
{
int lena=strlen(word1+1);
int lenb=strlen(word2+1);
memset(dp,0,sizeof(dp));
for(int i=1;i<=lena;i++)
for(int j=1;j<=lenb;j++)
{
if(word1[i]==word2[j])
{
dp[i][j]=dp[i-1][j-1]+1;
p[i][j]=1;
}
else if(dp[i][j-1]>=dp[i-1][j])
{
dp[i][j]=dp[i][j-1];
p[i][j]=2;
}
else
{
dp[i][j]=dp[i-1][j];
p[i][j]=3;
}
}
dfsprint(lena,lenb);
printf("\n");
}
}