UVa10635--Prince and Princess(LCS轉LIS)

題目:UVa10635


分析:由於每個序列中的所有元素各不相同,所以可以先將任意一個序列的元素,修改爲該序列中當前元素在另一個序列中對應元素的下標。沒有匹配的就設爲0或捨棄不要。這樣就將LCS問題轉化爲了LIS,時間複雜度就降下來了。


代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 300*300;

int n, p, q;
int c[maxn];
int num[maxn], dp[maxn];
int ans;

int main() {
    int T;
    scanf("%d", &T);
    for(int kase = 1; kase <= T; kase++) {
        scanf("%d%d%d", &n, &p, &q);
        memset(num, 0, sizeof(num));
        for(int i = 1; i <= p+1; i++) {
            int x;
            scanf("%d", &x);
            num[x] = i;
        }
        int cnt = 0;
        for(int i = 0; i < q+1; i++) {
            int x;
            scanf("%d", &x);
            if(num[x]) c[cnt++] = num[x];
        }
        ans = 0;
        for(int i = 0; i < cnt; i++) {
            dp[i] = 1;
            for(int j = i-1; j >= 0; j--) {
                if(c[i] > c[j]) {
                    dp[i] = max(dp[i], dp[j]+1);
                }
            }
            ans = max(ans, dp[i]);
        }
        printf("Case %d: %d\n", kase, ans);
    }
    return 0;
}


發佈了172 篇原創文章 · 獲贊 15 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章