HDU 1423 Greatest Common Increasing Subsequence(LICS)

最长上升公共子序列

#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;

int n, m, a[505], b[505];
int dp[505][505];//以a[i]结尾的最长公共上升子序列长度

int LICS() {

    int MAX, i, j;
    memset(dp, 0, sizeof(dp));

    for(i = 1; i <= n; i++) {
        MAX = 0;
        for(j = 1; j <= m; j++) {

            dp[i][j] = dp[i-1][j];//初始化

            //寻找前面最长上升子序列
            if(a[i] > b[j] && MAX < dp[i-1][j]) {
                MAX = dp[i-1][j];
            } else if(a[i] == b[j]){//可以配对
                dp[i][j] = MAX + 1;
            }
        }
    }

    MAX = 0;
    for(i = 1; i <= m; i++)
        if(MAX < dp[n][i])
            MAX = dp[n][i];

    return MAX;
}

int main() {
    //freopen("data.in", "r", stdin);
    int i, t;
    scanf("%d", &t);
    while(t--) {

        scanf("%d", &n);
        for(i = 1; i <= n; i++)
            scanf("%d", &a[i]);

        scanf("%d", &m);
        for(i = 1; i <= m; i++)
            scanf("%d", &b[i]);

        printf("%d\n", LICS());
        if(t)
            printf("\n");
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/ccshijtgc/article/details/80930944
今日推荐