假·最大子段和 (sdutoj 4359 首尾相连)(思维)

题目链接:http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2736/pid/4359

具体思路: 首先分析一波,最大的连续字段和只有两种情况,第一中,在 n个中间直接找,第二种.这个数组的尾部取几个,然后再从头部找出几个,使得总和最大.

然后思路就来了,对于第一种情况,我们直接线性的跑过去就可以了.对于第二种情况,我们可以对整个数组进行取反,然后再对取反后的数组求一个最大连续和,这样就相当于求原数组的最小的一段相连的,那么剩下的就是第二种情况的最大连续和的最优解了(学弟学妹们太强了,,,,我已经跟不上节奏了---)

AC代码:

#include<iostream>
#include<cstring>
#include<iomanip>
#include<stdio.h>
#include<algorithm>
using namespace std;
# define inf 0x3f3f3f3f
# define ll long long
const int maxn = 200000+100;
int a[maxn];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
ll sum=0;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
ll tmp1=0,ans1=0,ans2=0;
for(int i=1;i<=n;i++){
tmp1+=a[i];
ans1=max(ans1,tmp1);
if(tmp1<0)tmp1=0;
}
tmp1=0;
for(int i=1;i<=n;i++){
tmp1+=(-a[i]);
ans2=max(ans2,tmp1);
if(tmp1<0)tmp1=0;
}
printf("%lld
",max(sum+ans2,ans1));
}
return 0;
}
原文地址:https://www.cnblogs.com/letlifestop/p/10262773.html