UVa 111 History Grading (最长公共子序列)

题意:

求两个事件序列的最长公共子序列,而题目中输入的是每个事件发生的时间,因而要先根据每个事件发生的时间把事件的序列的找到。

比如如果输入是1 3 4 2,那么实际上事件序列是1 4 2 3

思路:

#include <cstdio>
#include <cstdlib>
#include <cstring>

#define max(a,b) (((a) > (b)) ? (a) : (b))
const int MAXN = 30;
int a[MAXN], b[MAXN], dp[MAXN][MAXN];

bool init(int n)
{   
    for (int i = 1; i <= n; ++i)
    {
        int t;
        if (scanf("%d", &t) != 1)
            return false;
        b[t] = i;
    }
    return true;
}

void solve(int n)
{
    memset(dp, 0, sizeof(dp));
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            if (a[i] == b[j])
                dp[i][j] = dp[i-1][j-1] + 1;
            else
                dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
        }
    }
    printf("%d\n", dp[n][n]);
}

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

    while (init(n))
       solve(n); 

    return 0;
}
-------------------------------------------------------

kedebug

Department of Computer Science and Engineering,

Shanghai Jiao Tong University

E-mail: kedebug0@gmail.com

GitHub: http://github.com/kedebug

-------------------------------------------------------

原文地址:https://www.cnblogs.com/kedebug/p/2764212.html