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

hdu1003

时间:2014-10-25 20:02:00      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   for   sp   div   on   

  求和最大的子串,取和以及首尾的位置。

  O(n2)的复杂度显然tle,线性O(n)一扫即可。维护一个sum值,当sum小于0时,sum清空,否则sum累加,并和maxn值比较。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 #define inf 0x7fffffff
 6 
 7 int main() {
 8     int cas = 0;
 9     int n, t, num, e, a, ans_num;
10     scanf("%d", &t);
11     while(t--) {
12         num = 0;
13         scanf("%d", &n);
14         int maxn = -inf;
15         int sum = 0;
16         for(int i=1; i<=n; i++) {
17             scanf("%d", &a);
18             sum += a;
19             num++;
20             if(sum >= maxn) {
21                 maxn = sum;
22                 e = i;
23                 ans_num = num;
24             } 
25             if(sum < 0) {
26                 sum = 0;
27                 num = 0;
28             }    
29         }
30         printf("Case %d:\n%d %d %d\n", ++cas, maxn, e - ans_num + 1, e);
31         if(t) puts("");
32     }
33     return 0;
34 } 
35 
36 
37 /*
38 3
39 5 -1 -2 1 2 -1
40 7 0 6 -1 1 -6 7 -5
41 
42 Case 1:
43 3 3 4
44 
45 Case 2:
46 7 1 6*/

 

hdu1003

标签:style   blog   color   io   os   for   sp   div   on   

原文地址:http://www.cnblogs.com/bigbigsunrise/p/4050773.html

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