zoukankan      html  css  js  c++  java
  • 最长上升子序列

    Description

    求最长上升子序列。

    Input

    单测试用例。

    第一行是一个正整数n,0 < n ≤ 3000

    第二行是n个非负整数。

    Output

    两行结果。

    第一行是最长上升子序列的长度。

    第二行是任意一个最长上升子序列,每个整数后面跟一个空格。

    Sample Input

    8
    5 2 8 6 3 6 9 7

    Sample Output

    4
    2 3 6 7

    代码演示

    #include<iostream>
    using namespace std;
    int main(){
        int n;int a[3002],b[3002]={0}, c[3002];
        cin >> n;
        b[1]=1;
        for(int i=1;i<=n;i++){
            cin >> a[i];
        }
        int max =0;
        for(int i=2;i<=n;i++){
            int k=0;
            for(int j=1;j<i;j++){
                if(a[j]<a[i]&&k<b[j]) //a[j]不能等于a[i],防止在连续相等的情况下,如 2 2
                    k=b[j];
                b[i]=k+1;
                if(max<b[i]){
                    max = b[i];
                }
            }
        }
        cout << max <<endl;
        //以上代码已经计算出最长上升子序列的长度
        //下面利用上面得到的b[i]计算出最长上升子序列
        int count = 1;
        c[1]=a[1];
        for(int i=1;i<n;i++)
            if(b[i]==b[i+1])
                c[count] = a[i+1];
            else if(b[i]<b[i+1]){
                c[++count] = a[i+1];
            }
            else b[i+1]=b[i];
        for(int i=1;i<=count;i++){
            cout << c[i] << " ";
        }
        return 0;
    }
  • 相关阅读:
    2333
    STL string
    后缀自动机的应用
    省选一轮
    等价类计数问题(Polya定理和burnside引理)
    Prufer序列与树的计数(坑)
    分治算法
    生成函数
    莫队算法
    Xamarin 技术解析
  • 原文地址:https://www.cnblogs.com/dichuan/p/7788862.html
Copyright © 2011-2022 走看看