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

HDU1159 && POJ1458:Common Subsequence(LCS)

2014-12-12 22:46 447 查看
必须得啃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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: