Problem Description
This is a problem from ZOJ 2432.To make it easyer,you just need output the length of the subsequence.
Input
Each sequence is described with M - its length (1 <= M <= 500) and M integer numbers Ai (-2^31 <= Ai < 2^31) - the sequence itself.
Output
output print L - the length of the greatest common increasing subsequence of both sequences.
Sample Input
1
5
1 4 2 5 -12
4
-12 1 2 4
2
题意:
求最大公共上升子序列。
思路:
用到了动态规划思想,求a序列前i个数和b序列前j个数中,最大的公共上升子序列长度,dp[i][j] = max(dp[i][j], dp[i][j - 1] + 1/0)。从a序列的第一个数向后更新,每次比较当前子序列是否上升,是则继承之前的最大dp[i][j],最后输出数组中的最大值。
#pragma once
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <iterator>
#include <sstream>
#include <fstream>
#include <list>
#define MST(a, b) memset(a, b, sizeof a);
using namespace std;
typedef long long ll;
const int MAXN = 500 + 10;
const int INF = 0x3f3f3f3f;
int main() {
int t, n, m;
int dp[MAXN][MAXN], numa[MAXN], numb[MAXN];
bool flag = false;
cin >> t;
for (int tt = 1; tt <= t; tt++) {
MST(dp, 0); MST(numa, 0); MST(numb, 0);
if (flag) cout << endl;
else flag = true;
cin >> n;
for (int i = 0; i < n; i++) cin >> numa[i];
cin >> m;
for (int i = 0; i < m; i++) cin >> numb[i];
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int k = 0; k < i; k++)
if (numa[i] > numa[k]) dp[i][j] = max(dp[i][j], dp[k][j]);
if (numa[i] == numb[j])
dp[i][j] = max(dp[i][j], dp[i][j - 1] + 1);
else
dp[i][j] = max(dp[i][j], dp[i][j - 1]);
res = max(res, dp[i][j]);
}
}
cout << res << endl;
}
}