标签:链接 special ast eth contain bsp eating this ++
InputEach line of the input contains two strings that represent the names of the fruits that should be combined. All names have a maximum length of 100 and only consist of alphabetic characters.
Input is terminated by end of file.
OutputFor each test case, output the shortest name of the resulting fruit on one line. If more than one shortest name is possible, any one is acceptable.
apple peach ananas banana pear peach
appleach bananas pearch
复习一下dp解决最长公共子序列问题····
关于这类问题参考:http://blog.csdn.net/yysdsyl/article/details/4226630/,这里就不多说了···
这道题其实和要求输出最长公共子序列问题的方法基本是一样的··只不过在dfs时除了要输出最长公共子序列以外还要按顺序输出两个单词其他部分的子串·····详细见dfs时的输出·····
看不懂可以结合上面链接中画的图
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<ctime> #include<string> #include<cstring> #include<algorithm> #include<cctype> using namespace std; const int N=105; char s[N],t[N],ans[N]; int n,m,f[N][N],d[N][N]; inline void dp() { for(int i=1;i<=n;i++) d[i][0]=0; for(int i=1;i<=m;i++) d[0][i]=1; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { if(s[i]==t[j]) f[i][j]=f[i-1][j-1]+1,d[i][j]=2; else if(f[i][j-1]>f[i-1][j]) f[i][j]=f[i][j-1],d[i][j]=1; else f[i][j]=f[i-1][j],d[i][j]=0; } } inline void dfs(int x,int y) { if(x==0&&y==0) return; else { if(d[x][y]==2) {dfs(x-1,y-1);printf("%c",s[x]);} else if(d[x][y]==1) {dfs(x,y-1);printf("%c",t[y]);} else if(d[x][y]==0) {dfs(x-1,y);printf("%c",s[x]);} } } int main() { freopen("a.in","r",stdin); while(~scanf("%s%s",s+1,t+1)) { memset(f,0,sizeof(f));memset(d,0,sizeof(d)); n=strlen(s+1);m=strlen(t+1); dp();dfs(n,m);printf("\n"); } return 0; }
刷题总结——advanced fruits(hud1503)
标签:链接 special ast eth contain bsp eating this ++
原文地址:http://www.cnblogs.com/AseanA/p/7644326.html