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

    好久没更博客了,最近又是要准备poj考试,看到了这道题,记得算法设计与分析课上有讲过,但是一直想不起最优的做法,搞了好久,最后看了看数据规模就用傻逼方法A了。

    总时间限制: 2000ms 内存限制: 65536kB
    描述
    A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (a1, a2, ..., aN) be any sequence (ai1, ai2, ..., aiK), where 1 <= i1 < i2 < ... < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8).
    
    Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.
    输入
    The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000
    输出
    Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.
    样例输入
    7
    1 7 3 5 9 4 8
    样例输出
    4
    来源
    Northeastern Europe 2002, Far-Eastern Subregion

    最优的做法应该是这样的:

      核心思想是要维护一个递增序列,每访问到一个数据的时候,可以通过这个递增序列查到当前比自己小的数据能够组成的上升序列最长为多少。具体做法:  初始的时候,递增链表为空,从头开始遍历该数组,将第一个数字加入到链表中,然后继续访问,当访问到的数字比当前链表末尾数字还大的时候,将该数字添加到链表中,当访问到的数字比当前链表的末尾数字要小的时候,则反向查询该链表,直到找到第一个比访问到的数字要小的数字时,将访问到的数字替换掉链表中查询到的数字的下一个数字。遍历完整个数组之后,链表的长度即为该数组的最长上升子序列的长度。时间复杂度为O(nk),k为链表的长度。

      当然我看到有人的具体做法是用数组来维护这个递增序列,而不是链表,而因为这个数组是递增的,所以每次查询的时候可以用二分查找来做,那样的话时间复杂度为O(nlogk),有兴趣可以看这篇博客,里面介绍得很清楚,还有例子!

    我的弱B代码贴在下面,大家看看就好 0 0

    #include <iostream>
    using namespace std;
    int a[1001]={0};
    int len[1001]={0};
    int main()
    {
        int n;
        while(cin>>n){
            len[0] = 1;
            for(int i = 0; i < n; i ++){
                cin>>a[i];
                int m = 0;
                for(int j = 0; j < i; j ++)
                {
                    if(m < len[j] && a[j] < a[i]){
                        m = len[j];
                    }
                        
                }
                len[i] = m+1;
            }
            int m = 0;
            for(int i = 0; i < n; i ++)
            {
                if(m < len[i])
                    m = len[i];
            }
            cout<<m<<endl;
        }
        return 0;
    }
  • 相关阅读:
    2015 年最受 Linux 爱好者欢迎的软硬件大盘点
    Java 9终于要包含Jigsaw项目了
    Linux 容器技术史话:从 chroot 到未来
    开发者最常用的 8 款 Sublime Text 3 插件
    60,000毫秒内对Linux的性能诊断效的方法
    bzoj 2595 [Wc2008]游览计划(斯坦纳树)
    bzoj 3997 [TJOI2015]组合数学(DP)
    bzoj 1014 [JSOI2008]火星人prefix(splay+hash)
    bzoj 1090 [SCOI2003]字符串折叠(区间DP)
    bzoj 1537 [POI2005]Aut- The Bus(DP+BIT)
  • 原文地址:https://www.cnblogs.com/xiaoshen555/p/3984836.html
Copyright © 2011-2022 走看看