zoukankan      html  css  js  c++  java
  • poj2127 Greatest Common Increasing Subsequence

    Greatest Common Increasing Subsequence
    Time Limit: 10000MS   Memory Limit: 65536K
    Total Submissions: 10113   Accepted: 2663
    Case Time Limit: 2000MS   Special Judge

    Description

    You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal possible length. 
    Sequence S1 , S2 , . . . , SN of length N is called an increasing subsequence of a sequence A1 , A2 , . . . , AM of length M if there exist 1 <= i1 < i2 < . . . < iN <= M such that Sj = Aij for all 1 <= j <= N , and Sj < Sj+1 for all 1 <= j < N .

    Input

    Each sequence is described with M --- its length (1 <= M <= 500) and M integer numbers Ai (-231 <= Ai < 231 ) --- the sequence itself.

    Output

    On the first line of the output file print L --- the length of the greatest common increasing subsequence of both sequences. On the second line print the subsequence itself. If there are several possible answers, output any of them.

    Sample Input

    5
    1 4 2 5 -12
    4
    -12 1 2 4

    Sample Output

    2
    1 4

    Source

    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    int f[1010][1010], a[1010], b[1010], n, m, last, id[1010][1010], ly;
    void print(int i, int j, int pos, int& first)
    {
        if (j == 0)return ;
        print(i-1,id[i][j], j, first);
        if (j != pos)
        {
            if (first)
            {
                printf("%d", b[j]);
                first = 0;
            }
            else printf(" %d", b[j]);
        }
    }
    int main()
    {
    while (~scanf("%d", &n))
    {
        for (int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        scanf("%d", &m);
        for (int i = 1; i <= m; i++)
            scanf("%d", &b[i]);
        memset(f, 0, sizeof(f));
        for (int i = 1; i <= n; i++)
        {
            int maxx = 0;ly = 0;
            for (int j = 1; j <= m; j++)
            {
                f[i][j] = f[i-1][j];
                id[i][j] = j;
                if (a[i] > b[j]&&maxx < f[i-1][j]){maxx = f[i-1][j];ly = j;}
                if (a[i] == b[j]){
                    f[i][j] = maxx + 1;
                    id[i][j] = ly;
                }
            }
        }
        int maxx = 0;
        for (int i = 1; i <= m; i++)
            if (maxx < f[n][i]){
                maxx = f[n][i];
                last = i;
            }
        printf("%d
    ", maxx);
        int first = 1;
        print(n, last, 0, first);
        printf("
    ");
    }
    }
  • 相关阅读:
    php如何导出csv文件(代码示例)
    【转】Linux 进程终止后自动重启
    【转】小程序web-view覆盖原生组件
    搭建 LNMP 环境
    数据库索引的底层原理
    NoSQL 介绍
    MySQL Explain详解
    centos搭建 SVN 服务器
    【转】提高mysql千万级大数据SQL查询优化30条经验(Mysql索引优化注意)
    优化mysql slave的同步速度
  • 原文地址:https://www.cnblogs.com/z52527/p/4681170.html
Copyright © 2011-2022 走看看