51nod-最长公共子序列问题

来源:互联网 发布:阿里云迁移工具 编辑:程序博客网 时间:2024/05/18 13:23


<span style="font-size:18px;">/*估计如果让输出最长子序列的个数会很简单,但是输出序列就不容易了,其实你在看题目给出的二维表从下向上是可以发现规律的,只有相同时才会输出 */#include<cstdio>#include<cstring>char a[1200],b[1200];int lcs[1200][1200];char temp[1200];int max(int u,int v){if(u>v)return u;return v;}int main(){int i=1,j=1;char ch;while((ch=getchar())!='\n'){a[i++]=ch;}while((ch=getchar())!='\n'){b[j++]=ch;}int ai,bj;for(ai=0;ai<i;++ai){for(bj=0;bj<j;++bj){if(ai==0||bj==0)lcs[ai][bj]=0;else if(a[ai]==b[bj]){lcs[ai][bj]=lcs[ai-1][bj-1]+1;}elselcs[ai][bj]=max(lcs[ai-1][bj],lcs[ai][bj-1]);}}int ans=0;for(--i,--j;i>=1&&j>=1;){if(a[i]==b[j]){temp[ans++]=a[i];--i;--j;}else if(lcs[i-1][j]>=lcs[i][j-1])--i;else--j;}for(--ans;ans>=0;--ans)printf("%c",temp[ans]);printf("\n");return 0;}</span>


0 0