您的位置:首页 > 其它

51nod 1254 最大子段和 V2 ——单调栈

2017-08-28 19:16 477 查看
N个整数组成的序列a[1],a[2],a[3],…,a
,你可以对数组中的一对元素进行交换,并且交换后求a[1]至a
的最大子段和,所能得到的结果是所有交换中最大的。当所给的整数均为负数时和为0。 例如:{-2,11,-4,13,-5,-2, 4}将 -4 和 4 交换,{-2,11,4,13,-5,-2, -4},最大子段和为11 + 4 + 13 = 28。   Input
第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N + 1行:N个整数(-10^9 <= A[i] <= 10^9)
Output
输出交换一次后的最大子段和。
Input示例
7
-2
11
-4
13
-5
-2
4
Output示例
28
——————————————————————————————
这道题可以做到O(n) 但是瓶颈在读入
[code]#include<stdio.h> #include<cstring> #include<algorithm> #define LL long long using namespace std; const int M=55007; const LL inf=1e15; char buf[11*M],*ptr=buf-1; int read(){ int ans=0,f=1,c=*++ptr; while(c<'0'||c>'9'){if(c=='-') f=-1; c=*++ptr;} while(c>='0'&&c<='9'){ans=ans*10+(c-'0'); c=*++ptr;} return ans*f; } int n; LL c[M],v[M],s[M],mx[M],mxh,ans; int cnt; struct node{LL mn,h;}q[M]; void solve(){ mxh=-inf; cnt=0; for(int i=n;i;i--) s[i]=s[i+1]+v[i],mx[i]=max(mx[i+1],v[i]); for(int i=1;i<=n;i++){ LL nowh=s[i]; while(cnt&&q[cnt].mn>=v[i]) nowh=max(nowh,q[cnt].h),cnt--; q[++cnt].mn=v[i]; q[cnt].h=nowh; mxh=max(mxh,nowh-v[i]); ans=max(ans,mxh-s[i+1]+mx[i+1]); } } int main(){ fread(buf,1,sizeof(buf),stdin); n=read(); for(int i=1;i<=n;i++) v[i]=read(); v[n+1]=-inf; for(int i=n;i;i--) s[i]=s[i+1]+v[i],mx[i]=max(mx[i+1],v[i]); solve(); reverse(v+1,v+1+n); solve(); printf("%lld\n",ans); return 0; }
View Code

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: