HDU 1159
Common Subsequence
最长公共子序列(LCS)
题目链接
解释
这个是《算法竞赛从入门到进阶》的例题,就不是剽窃书上的讲解了。
过题代码
普通版
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXN = 6000;
const int MAXM = 6000;
char s1[MAXN];
char s2[MAXM];
int dp[MAXN][MAXM];
int n,m;
int solve()
{
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (s1[i] == s2[j])
{
dp[i][j] = dp[i-1][j-1]+1;
}
else
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n][m];
}
int main()
{
while (~scanf("%s%s", s1+1, s2+1))
{
n = strlen(s1+1);
m = strlen(s2+1);
printf("%d\n", solve());;
}
return 0;
}
滚动数组
这个如果直接用一维,试了一下感觉比较复杂,就用了二维。
emmm翻个倍空间差不多,我觉得问题不是很大。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXN = 6000;
const int MAXM = 6000;
char s1[MAXN];
char s2[MAXM];
int dp[2][MAXM];
int n,m;
int solve()
{
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (s1[i] == s2[j])
{
dp[i%2][j] = dp[(i-1)%2][j-1]+1;
}
else
{
dp[i%2][j] = max(dp[(i-1)%2][j], dp[i%2][j-1]);
}
}
}
return dp[n%2][m];
}
int main()
{
while (~scanf("%s%s", s1+1, s2+1))
{
n = strlen(s1+1);
m = strlen(s2+1);
printf("%d\n", solve());;
}
return 0;
}