码迷,mamicode.com
首页 > 其他好文 > 详细

最长升序子序列

时间:2015-08-13 12:02:10      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:

Description

Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14. 
 

Input

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000). 
 

Output

For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases. 
 

Sample Input

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
 

Sample Output

Case 1: 14 1 4
Case 2: 7 1 6
 
 
 
思路:
       用二分法(避免超时)找最小的数放在子序列里面,比如最开始的序列是 2 3 4,但是后面又发现了一个1,就把1代替之前的2,以免后面出现更长的子序列
 
 
 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 #define  maxn 100000+10
 5 int al[maxn], cl[maxn];
 6 int main()
 7 {
 8     int n,len,left,right,mid;
 9     while (scanf("%d",&n)!= EOF){
10         for (int i = 0; i < n; i++)
11             scanf("%d", &al[i]);
12         len = 0, cl[0] = -1;
13         for (int i = 0; i < n; i++)
14         {
15             if (al[i]>cl[len])
16                 cl[++len] = al[i];    //把大的数放进去
17             else
18             {
19                 left = 1, right = len;    //二分法找后面小的数放在这个子序列的前面,以免有更长的子序列
20                 
21                 while (left <= right)
22                 {
23                     mid = (left + right) / 2;
24                     if (al[i]>cl[mid])
25                         left = mid + 1;
26                     else
27                        right = mid - 1;
28                 }
29                 cl[left] = al[i];
30             }
31         }
32         printf("%d\n", len);
33     }
34     
35     return 0;
36 }

 

 
 

最长升序子序列

标签:

原文地址:http://www.cnblogs.com/Lynn0814/p/4726667.html

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