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




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM