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



转载于:https://www.cnblogs.com/danscarlett/p/5656464.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值