两种方法,贪心和dp
例题:hdu 1003
贪心如下:
用一个初始值为极小的变量maxsum存待求的最大字段和,用sum累加数列中每个数,如果sum大于maxsum,就把sum赋值给maxsum,然后更新数据,start和end变量只存最终结果,不参与运算,另开一个扫过变量p参与运算与变量更新
代码如下
#include<iostream>
#include<climits>
using namespace std;
int a;
using ll = long long;
int ret = 0;
void solve() {
int n; cin >> n;
ret++;
ll maxsum = INT_MIN;
int start = 1; int end = 1; int p = 1;//开始,结束,扫过
ll sum = 0;
for (int i = 1; i <= n; i++) {
cin >> a;
sum += a;
if (sum > maxsum) { maxsum = sum; start = p;end=i; }//maxsum用来记录更新最大值
if (sum < 0) {
sum = 0;
p = i + 1;//更新开头,如果这次宿命比maxsum大,就走上次的if赋值maxsum
}
}
printf("Case %d:\n", ret);
cout << maxsum << ' ' << start << ' ' << end << '\n';
cout << '\n';
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t; cin >> t;
while (t--) {
solve();
}
return 0;
}