码迷,mamicode.com
首页 > 其他好文 > 详细

【动态规划】最长上升公共子序列

时间:2015-07-31 23:17:22      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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

int a[505], b[505];
int dp[505], path[505];
int Susake_lcis[505][505];

void Susake_LCIS(int a[], int la, int b[], int lb)
{
    memset(path, 0, sizeof(path));
    memset(Susake_lcis, 0, sizeof(Susake_lcis));
    memset(dp, 0, sizeof(dp));
    int i, j, k, Max;
    for(i = 1; i <= la; i++) {
        memcpy(Susake_lcis[i], Susake_lcis[i-1], sizeof(Susake_lcis[0]));
        for(k = 0, j = 1; j <= lb; j++)
        {
            if(b[j - 1] < a[i - 1] && dp[j] > dp[k]) k = j;
            if(b[j - 1] == a[i - 1] && dp[k] + 1 > dp[j])
            {
                dp[j] = dp[k] + 1,
                Susake_lcis[i][j] = i * (lb + 1) + k;
            }
        }
    }
    for(Max = 0, i = 1; i <= lb; i++)
        if(dp[i] > dp[Max])
            Max = i;
    for(i = la * lb + la + Max, j = dp[Max]; j; i = Susake_lcis[i / (lb + 1)][i % (lb + 1)], j--)
        path[j] = b[i % (lb + 1) - 1];
    printf("%d\n", dp[Max]);
    if(Max)
    {
        if(dp[Max] == 1)
            printf("%d\n", path[1]);
        else
        {
            for(int i = 1; i <= dp[Max] - 1; i++)
                printf("%d ", path[i]);
            printf("%d\n", path[dp[Max]]);
        }
    }
}

int main(int argc, char *argv[])
{
    int n, m;
    while(scanf("%d", &n) != EOF)
    {
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);
        scanf("%d", &m);
        for(int i = 0; i < m; i++) scanf("%d", &b[i]);
        Susake_LCIS(a, n, b, m);
    }
    return 0;
}

 

【动态规划】最长上升公共子序列

标签:

原文地址:http://www.cnblogs.com/Susake/p/4693242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!