码迷,mamicode.com
首页 > 编程语言 > 详细

poj 2757 : 最长上升子序列(JAVA)

时间:2016-07-09 20:41:24      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

总时间限制: 
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



poj 2757 : 最长上升子序列(JAVA)

标签:

原文地址:http://www.cnblogs.com/danscarlett/p/5656464.html

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