HDU1159 && POJ1458:Common Subsequence(LCS)

来源:互联网 发布:数据库开发需要学什么 编辑:程序博客网 时间:2024/04/28 06:19

必须得啃DP了,就从最简单的DP入门题开始了。

#include <iostream>#include <cstdio>#include <string>#include <cstring>using namespace std;string str1,str2;int pos[1005][1005];int main(){while(cin>>str1>>str2){int length1=str1.size();int length2=str2.size();memset(pos,0,sizeof(pos));for(int i=1;i<=length1;i++){for(int j=1;j<=length2;j++){if(str1[i-1]==str2[j-1]){pos[i][j]=pos[i-1][j-1]+1;}else{pos[i][j]=max(pos[i-1][j],pos[i][j-1]);}}}cout<<pos[length1][length2]<<endl;}return 0;}
滚动数组优化

#include <iostream>#include <cstdio>#include <string>#include <cstring>using namespace std;string str1,str2;int pos[2][1005];int main(){while(cin>>str1>>str2){int length1=str1.size();int length2=str2.size();memset(pos,0,sizeof(pos));for(int i=1;i<=length1;i++){for(int j=1;j<=length2;j++){if(str1[i-1]==str2[j-1]){pos[i%2][j]=pos[(i-1)%2][j-1]+1;}else{pos[i%2][j]=max(pos[(i-1)%2][j],pos[i%2][j-1]);}}}cout<<max(pos[0][length2],pos[1][length2])<<endl;}return 0;}




0 0
原创粉丝点击