hdu 1423 最长公共上升子序列, 题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1423
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define N 505
int ncase, n, m, a[N], b[N], dp[N][N];
int main()
{
scanf("%d", &ncase);
while (ncase--)
{
scanf("%d", &n);
for (int i=1; i<=n; i++)
scanf("%d", &a[i]);
scanf("%d", &m);
for (int i=1; i<=m; i++)
scanf("%d", &b[i]);
memset(dp, 0, sizeof(dp));
//dp[i][j]表示序列a[1...i]和序列b[1...j]的最长公共上升子序列
for (int i=1; i<=n; i++)
{
int temp = 0;
for (int j=1; j<=m; j++)//用a[i]与b[1...j]每一位进行比较
{
if (a[i]>b[j] && dp[i-1][j]>temp)
temp = dp[i-1][j];//temp表示序列a[i-1]与序列b[1...j]的最长公共上升子序列
if (a[i] == b[j])
dp[i][j] = temp+1;//若a[i]和b[j]相等
else
dp[i][j] = dp[i-1][j];//若a[i]和b[j]不等
}
}
int Max = 0;
for (int i=1; i<=m; i++)
if (dp[n][i]>Max)
Max = dp[n][i];
printf("%d\n", Max);
if (ncase)
printf("\n");
}
return 0;
}
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define N 505
int ncase, n, m, a[N], b[N], dp[2][N];
int main()
{
scanf("%d", &ncase);
while (ncase--)
{
scanf("%d", &n);
for (int i=1; i<=n; i++)
scanf("%d", &a[i]);
scanf("%d", &m);
for (int i=1; i<=m; i++)
scanf("%d", &b[i]);
memset(dp, 0, sizeof(dp));
//dp[i][j]表示序列a[1...i]和序列b[1...j]的最长公共上升子序列
for (int i=1; i<=n; i++)
{
int temp = 0;
for (int j=1; j<=m; j++)//用a[i]与b[1...j]每一位进行比较
{
if (a[i]>b[j] && dp[(i-1)%2][j]>temp)
temp = dp[(i-1)%2][j];//temp表示序列a[i-1]与序列b[1...j]的最长公共上升子序列
if (a[i] == b[j])
dp[i%2][j] = temp+1;//若a[i]和b[j]相等
else
dp[i%2][j] = dp[(i-1)%2][j];//若a[i]和b[j]不等
}
}
int Max = 0;
for (int i=1; i<=m; i++)
if (dp[n%2][i]>Max)
Max = dp[n%2][i];
printf("%d\n", Max);
if (ncase)
printf("\n");
}
return 0;
}