http://acm.hdu.edu.cn/showproblem.php?pid=1231
Dp[i] 以a[i]元素结尾的子序列的最大和
记录 再记录一下起始位置即可
1 #include <iostream> 2 #include <string.h> 3 #include <stdio.h> 4 using namespace std; 5 6 int a[10007]; 7 int dp[10007]; 8 int st[10007]; 9 int main() 10 { 11 int n; 12 while(cin >> n) 13 { 14 bool neg = true; 15 if (!n) break; 16 memset(dp, 0 ,sizeof(dp)); 17 for (int i = 0; i < n; i++) 18 { 19 scanf("%d", &a[i]); 20 if (a[i] >= 0) neg = false; 21 } 22 if (neg) 23 { 24 cout << 0 << " " << a[0] << " " << a[n-1] << endl; 25 continue; 26 } 27 dp[0] = a[0]; 28 st[0] = 0; 29 for (int i = 1; i < n; i++) 30 { 31 if (dp[i-1]+a[i] > a[i]) 32 { 33 dp[i] = dp[i-1]+a[i]; 34 st[i] = st[i-1]; 35 } 36 else 37 { 38 dp[i] = a[i]; 39 st[i] = i; 40 } 41 } 42 int ans = -1e9; 43 int index = 0; 44 for (int i = 0; i < n; i++) 45 { 46 if(ans < dp[i]) 47 { 48 index = i; 49 ans = dp[i]; 50 } 51 } 52 cout << ans << " " << a[st[index]] << " " << a[index] << endl; 53 } 54 return 0; 55 }