贪心
#include<iostream>
using namespace std;
const int INF = 0x7fffffff;
int main() {
int T;
cin >> T;
for (int i = 1; i <= T; i++) {
int N;
cin >> N;
//初始化最大和为无穷大的负数,防止第一个数为负数
int maxsum = -INF;
int start = 1, end = 1, p = 1;//起点,终点,扫描位置
int sum = 0;//当前子序和
for (int j = 1; j <= N; j++) {
int n;
cin >> n;
sum += n;
//更新最大子序和
if (sum > maxsum) {
maxsum = sum;
start = p;
end = j;
}
//如果sum是负数,会使后续的子序和变小,所以从下一个数字开始重新求和
if (sum < 0) {
sum = 0;
p = j + 1;
}
}
cout << "Case " << i << ":" << endl;
cout << maxsum << " " << start << " " << end << " " << endl;
if (i != T)cout << endl;
}
}
动态规划
#include<iostream>
using namespace std;
int dp[100005];//dp[i]是以第i个数结尾的最大值
//dp[i]可能只有一个元素,即a[i]
//dp[i]包含多个元素,即dp[i-1]+a[i]
//所以dp[i]=max(dp[i-1]+a[i],a[i])
//maxsum就是dp[i]的最大值
int main() {
int T;
cin >> T;
for (int i = 1; i <= T; i++) {
int N;
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> dp[i];//用dp[]储存a[]
}
int start = 1, end = 1, p = 1;
int maxsum = dp[1];
for (int i = 2; i <= N; i++) {
//dp[i-1]+a[i]>=a[i]
if (dp[i - 1] + dp[i] >= dp[i]) {
dp[i] = dp[i - 1] + dp[i];
}
//dp[i-1]+a[i]<a[i]
else {
p = i;
}
if (dp[i] > maxsum) {
maxsum = dp[i];
start = p;
end = i;
}
}
cout << "Case " << i << ":" << endl;
cout << maxsum << " " << start << " " << end << " " << endl;
if (i != T)cout << endl;
}
}