首先介绍分治的方法:
在分治求最大连续和的过程中,维护一个区间,找到最大连续和的时候就替换区间
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
const int MAXN = 100000+10;
typedef struct node {
int l, r;
int w;
}Num;
Num num[MAXN];
Num max_sum(int x, int y) {
if(y-x == 1) {
Num cns;
cns.w = num[x].w;
cns.l = x;
cns.r = x;
return cns;
}
int m = x+(y-x)/2;
Num cns;
Num num1 = max_sum(x, m);
Num num2 = max_sum(m, y);
if(num1.w <= num2.w) {
cns = num2;
}else cns = num1;
int res = 0;
int l, r;
int L = num[m-1].w;
int R = num[m].w;
for (int i = m-1; i >= x; i--) {
res +=num[i].w;
if(L <= res) {
L = res;
l = i;
}
}
res = 0;
for (int i = m; i < y; i++) {
res+= num[i].w;
if(R<=res) {
R = res;
r=i;
}
}
if(cns.w <= L+R) {
cns.w=L+R;
cns.l = l;
cns.r = r;
}
return cns;
}
int main() {
int t;
cin >> t;
int kase = 0;
while(t --) {
if(kase) cout << endl;
kase ++;
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> num[i].w;
}
cout << "Case "<< kase << ":" << endl;
Num ans = max_sum(1, n+1);
cout << ans.w << " " << ans.l << " " << ans.r << endl;
}
}