题目链接:
题解:
我数据结构真心是弱啊= =。
线段树好厉害啊,一直不会区间最大连续和,今天刚学习了一下233。
维护前缀最大和后缀最大,越界最大(?),再维护一个区间最大,瞎搞搞就好了,RE了一遍233。
代码:
1 #define Troy 2 3 #include <bits/stdc++.h> 4 5 using namespace std; 6 7 inline int read(){ 8 int s=0,k=1;char ch=getchar(); 9 while(ch<‘0‘|ch>‘9‘) ch==‘-‘?k=-1:0,ch=getchar(); 10 while(ch>47&ch<=‘9‘) s=s*10+(ch^48),ch=getchar(); 11 return s*k; 12 } 13 14 const int N=100005; 15 16 int n,m,a[N]; 17 18 struct node { 19 int l,r,val; 20 friend bool operator <(node x,node y){ 21 return x.val!=y.val?x.val<y.val:(x.l!=y.l?x.l>y.l:x.r>y.r); 22 } 23 friend node operator +(node x,node y){ 24 node z; 25 z.l=min(x.l,y.l);z.r=max(x.r,y.r); 26 z.val=x.val+y.val;return z; 27 } 28 inline void out(){printf("%d %d %d\n",l,r,val);} 29 }; 30 31 struct Tree{ 32 node prefix,suffix,middle,section; 33 Tree *lc,*rc; 34 }*root,tree[N*20],*ans;int cnt; 35 36 inline void update( Tree *u){ 37 u->middle=u->lc->suffix+u->rc->prefix; 38 u->prefix=max(u->lc->prefix,u->lc->section+u->rc->prefix); 39 u->suffix=max(u->rc->suffix,u->rc->section+u->lc->suffix); 40 u->section=u->lc->section+u->rc->section; 41 u->middle=max(u->middle,max(u->lc->middle,max(u->rc->middle,max(u->prefix,u->suffix)))); 42 } 43 44 inline void build(Tree *&u,int l,int r){ 45 u=tree+cnt;++cnt; 46 if(l==r){ 47 u->prefix=u->suffix=u->middle=u->section=(node){l,r,a[l]}; 48 return ; 49 } 50 int mid=l+r>>1; 51 build(u->lc,l,mid); 52 build(u->rc,mid+1,r); 53 update(u); 54 } 55 56 inline void query(Tree *u,int l,int r,int x,int y){ 57 if(x<=l&&r<=y){ 58 if(ans==NULL) ans=u; 59 else{ 60 Tree *now=ans;ans=tree+cnt,++cnt; 61 ans->lc=now,ans->rc=u; 62 update(ans); 63 } 64 return ; 65 } 66 int mid=l+r>>1; 67 if(x<=mid) query(u->lc,l,mid,x,y); 68 if(y>mid) query(u->rc,mid+1,r,x,y); 69 } 70 71 int main(){ 72 freopen("hill.in","r",stdin); 73 freopen("hill.out","w",stdout); 74 n=read(),m=read(); 75 for(int i=1;i<=n;++i) a[i]=read(); 76 build(root,1,n); 77 for(int i=1;i<=m;++i){ 78 int l=read(),r=read(); 79 ans=NULL;query(root,1,n,l,r); 80 ans->middle.out(); 81 } 82 }
时间: 2024-10-29 19:05:37