题目链接:HDU 1003 Max Sum
题目大意:
求出(n)个数字中的最大子序列和,并且输出起始和终止位置。
题解:
典型的DP题。
定义dp[i]为以第i个数为结尾的子序列的和的最大值,则状态转移方程为:
[dp[i] = num[i],i = 1
]
[dp[i] = max(dp[i - 1] + num[i], num[i]),i > 1
]
#include <iostream>
#include <cstring>
using namespace std;
#define ms(a, b) memset(a, b, sizeof(a))
#define io_speed_up ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
int dp[100010], t, n, l, r, index, maxn;
int main() {
io_speed_up;
cin >> t;
for (int kase = 1; kase <= t; ++kase) {
cin >> n;
ms(dp, 0);
for (int i = 1; i <= n; ++i) {
cin >> dp[i];
}
l = r = index = 1;
maxn = dp[1];
for (int i = 2; i <= n; ++i) {
if (dp[i - 1] >= 0) {
dp[i] += dp[i - 1];
} else {
index = i;
}
if (dp[i] > maxn) {
l = index;
r = i;
maxn = dp[i];
}
}
cout << "Case " << kase << ":" << endl;
cout << maxn << ' ' << l << ' ' << r << endl;
if (kase != t) {
cout << endl;
}
}
return 0;
}