Greatest Common Increasing Subsequence(HDOJ-1423)

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值