题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1159
题记:最简单的最长公共子序列问题,用dp解决即可。
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int dp[1005][1005];
string s1,s2;
int LCS(){
memset(dp,0,sizeof(dp));
for(int i=1;i<=s1.length();i++){
for(int j=1;j<=s2.length();j++){
if(s1[i-1]==s2[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
return dp[s1.length()][s2.length()];
}
int main(){
while(cin>>s1>>s2){
cout<<LCS()<<endl;
}
return 0;
}
用滚动数组优化之后的代码。
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int dp[2][1005];
string s1,s2;
int LCS(){
memset(dp,0,sizeof(dp));
for(int i=1;i<=s1.length();i++){
for(int j=1;j<=s2.length();j++){
if(s1[i-1]==s2[j-1])
dp[i%2][j]=dp[(i-1)%2][j-1]+1;
else
dp[i%2][j]=max(dp[i%2][j-1],dp[(i-1)%2][j]);
}
}
return dp[s1.length()%2][s2.length()];
}
int main(){
while(cin>>s1>>s2){
cout<<LCS()<<endl;
}
return 0;
}