Max Sum

http://acm.hdu.edu.cn/showproblem.php?pid=1003

感觉自己的dp弱爆了。。以前做的都忘得差不多了,只能从最基础的再学一遍吧。。

求最大连续子段和。要知道一个定理,即最大连续子段和中不可能包含负的子段和。对于序列(....i......j,j+1.....),如果sum(i,j) < 0,则下一个子段的起始位置就为j+1。

 1 #include <stdio.h>
 2 #include <string.h>
 3 const int N=100010;
 4 int a[N];
 5 int main()
 6 {
 7     int t,n,o = 0;
 8     scanf("%d",&t);
 9     while(t--)
10     {
11         o++;
12         scanf("%d",&n);
13         for (int i = 1; i <= n; i++)
14             scanf("%d",&a[i]);
15         int Max = -100010,sum = 0,s,e;
16         for (int i = 1,j = 1; j <= n; j++)
17         {
18             sum+=a[j];
19             if (sum >= Max)
20             {
21                 Max = sum;
22                 s = i;
23                 e = j;
24             }
25             if (sum < 0)//不能用else if,因为有全为负数的情况,在这里跪了好多次
26             {
27                 sum = 0;
28                 i = j+1;
29             }
30         }
31         printf("Case %d:
",o);
32         printf("%d %d %d
",Max,s,e);
33         if (t!=0)
34             puts("");
35     }
36     return 0;
37 }
View Code
原文地址:https://www.cnblogs.com/lahblogs/p/3574018.html