HDU1003 Max Sum dp C语言

View Code
  1 #include <cstdio>
2
3 #include <cstdlib>
4
5 #include <cstring>
6
7
8
9 #define MAXN (100000 + 100)
10
11 #define I64 __int64
12
13
14
15 int a[MAXN], f[MAXN];
16
17 I64 head, tail;
18
19 I64 nowh, nowt;
20
21 I64 res;
22
23
24
25 void Clear() {
26
27 memset(a, 0, sizeof(a));
28
29 memset(f, 0, sizeof(f));
30
31 res = -0x3333;
32
33 head = tail = 1;
34
35 nowh = nowt = 1; //nowhead, nowtail
36
37 }
38
39
40
41 int main() {
42
43 int t;
44
45 I64 n;
46
47 int count = 0;
48
49 I64 i, j;
50
51 scanf("%d", &t);
52
53 while(t--) {
54
55 Clear();
56
57 scanf("%I64d", &n);
58
59 for(i = 1; i <= n; i++) {
60
61 scanf("%d", &a[i]);
62
63 }
64
65 f[1] = a[1];
66
67 res = f[1];
68
69 for(j = 2; j <= n; j++) {
70
71 f[j] = (f[j - 1] + a[j]) > a[j] ? (f[j - 1] + a[j]) : a[j];
72
73 if(f[j] == f[j - 1] + a[j]) {
74
75 nowt = j;
76
77 }
78
79 else {
80
81 nowh = j;
82
83 nowt = j;
84
85 }
86
87 if(f[j] > res) {
88
89 res = f[j];
90
91 head = nowh;
92
93 tail = nowt;
94
95 }
96
97 }
98
99 printf("Case %d:\n%I64d %I64d %I64d\n", ++count, res, head, tail);
100
101 if(t)
102
103 printf("\n");
104
105 }
106
107 //system("pause");
108
109 return 0;
110
111 }

求一段数据的最大子段和,并记录首尾数据下标。

思路:储存数据在a[]中,f[j]为以i开头j结尾的子段和,若a[j]之前的和f[j - 1]a[j]的和(f[j - 1] + a[j]) 大于a[j],f[j] = (f[j - 1] + a[j])f[j]的起点为f[j - 1]的起点,终点为j;若(f[j - 1] + a[j]) 小于a[j],f[j] = a[j],起点等于终点为j;若f[j]大于resres等于f[j],同时更新最大子段和的起点终点坐标。

提交情况:1PE1AC

 

AC code

 

posted @ 2011-07-20 16:30  cloehui  阅读(157)  评论(0编辑  收藏  举报