zoukankan      html  css  js  c++  java
  • poj 2757 : 最长上升子序列(JAVA)

    总时间限制: 
    2000ms
     内存限制: 
    65536kB
    描述
    一个数的序列bi,当b1 < b2 < ... < bS的时候,我们称这个序列是上升的。对于给定的一个序列(a1a2, ..., aN),我们可以得到一些上升的子序列(ai1ai2, ..., aiK),这里1 <= i1 < i2 < ... < iK <= N。比如,对于序列(1, 7, 3, 5, 9, 4, 8),有它的一些上升子序列,如(1, 7), (3, 4, 8)等等。这些子序列中最长的长度是4,比如子序列(1, 3, 5, 8).

    你的任务,就是对于给定的序列,求出最长上升子序列的长度。
    输入
    输入的第一行是序列的长度N (1 <= N <= 1000)。第二行给出序列中的N个整数,这些整数的取值范围都在0到10000。
    输出
    最长上升子序列的长度。
    样例输入
    7
    1 7 3 5 9 4 8
    样例输出
    4
    
    来源
    翻译自 Northeastern Europe 2002, Far-Eastern Subregion 的比赛试题
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Main{
        public static void main(String[] args) 
        {
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();//序列长度 1-1000
            int[] l = new int[n],a = new int[n]; //以某一节点为重点的最长子序列的长度
            
            for(int i =0;i<n;i++)
            {
                a[i] = in.nextInt();//输入第i个数,下面计算它为终点的最长上升子序列
                if(i==0)    l[i] = 1;
                else
                {
                    int k = 0,longest = 0;
                    for(int j=0;j<i;j++)
                    {
                        if(a[j]<a[i])//比该数小的数组前面的数里
                        {
                            if(k == 0) longest = l[j];//第一个比他小
                            else
                            {
                                if(l[j] > longest)//找到最长的
                                    longest = l[j];
                            }
                            k++;
                        }//if
                        l[i] = longest+1;
                    }//for
                }//else
            }
            Arrays.sort(l);
            System.out.println(l[l.length-1]);
        }
    }

    Summary:

    This poj problem is another typical example for dynamic planning.Well, the idea is very delicate. I tried to calculate the longgest sbsequences before a certain number, but it couldn' make it out.

    Then I referred to the book, which is shameful to admit, I found an only too brilliant idea which is to caculate the longgest rising subsequences's lengths of one ended with a certain number. 

    As always, I got WA first time the first time I submitted my answer. Oh no..

    The reason for the failure lies in this sentance when initializing the value:

    I wrote "longest=1"..which triggers to a fault when the number happens to find no one before it can be less than itself: 

    longest = 0



  • 相关阅读:
    委托和事件的区别和联系(转载
    Captcha验证码识别走向3D化
    3DCaptcha for .net
    委托之异步(转自http://www.cnblogs.com/inforasc/archive/2009/10/21/1587756.html
    static的初始化顺序
    各式各样的验证码
    [SQL优化工具]SQL Tuning for SQL Server(转)
    浅析C#深拷贝与浅拷贝 (转载)
    [orcle] oracle截取字符串的函数substr
    struts2.0的工作原理
  • 原文地址:https://www.cnblogs.com/danscarlett/p/5656464.html
Copyright © 2011-2022 走看看