题目
题解
这道题是线段树,我们可以维护一个区间的Ans->必须取一个点的最大和,LAns->必须取左端点的最大和,RAns->必须去右端点的最大和,还有Sum->区间和。这样两个区间就可以轻松的合并成一个大区间了,脑补一下做法~好吧,这道题貌似查询的时候区间的左右端点顺序可能是反的QAQ注意一下。
代码
1 /*Author:WNJXYK*/ 2 #include<cstdio> 3 using namespace std; 4 5 inline void swap(int &x,int &y){int tmp=x;x=y;y=tmp;} 6 inline int remax(int a,int b){ 7 if (a>b) return a; 8 return b; 9 } 10 11 const int Maxn=500000; 12 struct Btree{ 13 int left,right; 14 int sum; 15 int lans,rans,ans; 16 }; 17 Btree tree[Maxn*4+10]; 18 int num[Maxn+10]; 19 20 void build(int x,int left,int right){ 21 tree[x].left=left; 22 tree[x].right=right; 23 if (left==right){ 24 tree[x].rans=tree[x].lans=tree[x].ans=num[left]; 25 tree[x].sum=num[left]; 26 }else{ 27 int mid=(left+right)/2; 28 build(x*2,left,mid); 29 build(x*2+1,mid+1,right); 30 tree[x].sum=tree[x*2].sum+tree[x*2+1].sum; 31 tree[x].ans=remax(tree[x*2].rans+tree[x*2+1].lans,remax(tree[x*2].ans,tree[x*2+1].ans)); 32 tree[x].lans=remax(tree[x*2].lans,tree[x*2].sum+tree[x*2+1].lans); 33 tree[x].rans=remax(tree[x*2+1].rans,tree[x*2].rans+tree[x*2+1].sum); 34 } 35 } 36 37 void change(int x,int loc,int val){ 38 if (tree[x].left==tree[x].right && tree[x].left==loc){ 39 tree[x].sum=val; 40 tree[x].rans=tree[x].lans=tree[x].ans=val; 41 }else{ 42 int mid=(tree[x].left+tree[x].right)/2; 43 if (loc<=mid){ 44 change(x*2,loc,val); 45 }else{ 46 change(x*2+1,loc,val); 47 } 48 tree[x].sum=tree[x*2].sum+tree[x*2+1].sum; 49 tree[x].ans=remax(tree[x*2].rans+tree[x*2+1].lans,remax(tree[x*2].ans,tree[x*2+1].ans)); 50 tree[x].lans=remax(tree[x*2].lans,tree[x*2].sum+tree[x*2+1].lans); 51 tree[x].rans=remax(tree[x*2+1].rans,tree[x*2].rans+tree[x*2+1].sum); 52 } 53 } 54 55 56 57 Btree _queryAns(int x,int left,int right){ 58 if (left<=tree[x].left && tree[x].right<=right){ 59 return tree[x]; 60 }else{ 61 int mid=(tree[x].left+tree[x].right)/2; 62 if (left>mid){ 63 return _queryAns(x*2+1,left,right); 64 }else if (right<mid+1){ 65 return _queryAns(x*2,left,right); 66 }else{ 67 Btree _Ans; 68 Btree tmp1,tmp2; 69 tmp1=_queryAns(x*2,left,right); 70 tmp2=_queryAns(x*2+1,left,right); 71 _Ans.sum=tmp1.sum+tmp2.sum; 72 _Ans.ans=remax(tmp1.rans+tmp2.lans,remax(tmp1.ans,tmp2.ans)); 73 _Ans.lans=remax(tmp1.lans,tmp1.sum+tmp2.lans); 74 _Ans.rans=remax(tmp2.rans,tmp1.rans+tmp2.sum); 75 return _Ans; 76 } 77 } 78 } 79 80 int n,m; 81 int k,a,b; 82 int main(){ 83 //freopen("b.in","r",stdin); 84 //freopen("b.out","w",stdout); 85 scanf("%d%d",&n,&m); 86 for (int i=1;i<=n;i++)scanf("%d",&num[i]); 87 build(1,1,n); 88 for (;m--;){ 89 scanf("%d%d%d",&k,&a,&b); 90 if (k==1){ 91 if (a>b) swap(a,b); 92 printf("%d\n",_queryAns(1,a,b).ans); 93 }else{ 94 change(1,a,b); 95 } 96 } 97 return 0; 98 }