您的位置:首页 > 其它

cqu 24915 这是一个标题(线段树区间合并)

2016-07-20 00:28 225 查看
链接:http://acm.cqu.edu.cn:8888/oj/problem_show.php?pid=24915

求区间内最大连续和

题解:区间合并基础题,区间每个节点需要维护一个结构体,里面存区间和,区间内最大连续和,最大前缀最大后缀。

然后pushup合并的时候,sum=lsum+rsum,maxn=max(lmaxn,rmaxn,lsuf+rpre),pre=max(lpre,lsum+rpre),suf=max(rsuf,rsum+lsuf)

就这个几个合并,然后在查询的时候呢,左边return一个结构体,右边return一个结构体,然后ans结构体也和上面一样合并,然后return ans

代码:

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")

using namespace std;
#define   MAX           200005
#define   MAXN          6005
#define   maxnode       15
#define   sigma_size    30
#define   lson          l,m,rt<<1
#define   rson          m+1,r,rt<<1|1
#define   lrt           rt<<1
#define   rrt           rt<<1|1
#define   middle        int m=(r+l)>>1
#define   LL            long long
#define   ull           unsigned long long
#define   mem(x,v)      memset(x,v,sizeof(x))
#define   lowbit(x)     (x&-x)
#define   pii           pair<int,int>
#define   bits(a)       __builtin_popcount(a)
#define   mk            make_pair
#define   limit         10000

//const int    prime = 999983;
const int    INF   = 0x3f3f3f3f;
const LL     INFF  = 0x3f3f;
const double pi    = acos(-1.0);
//const double inf   = 1e18;
const double eps   = 1e-8;
const LL    mod    = 1e9+7;
const ull    mx    = 133333331;

/*****************************************************/
inline void RI(int &x) {
char c;
while((c=getchar())<'0' || c>'9');
x=c-'0';
while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0';
}
/*****************************************************/

struct Node{
LL sum;
LL maxv;
LL maxl,maxr;
}p[MAX<<2];
LL a[MAX];
void pushup(int rt){
p[rt].sum=p[lrt].sum+p[rrt].sum;
p[rt].maxv=max(max(p[lrt].maxv,p[rrt].maxv),p[lrt].maxr+p[rrt].maxl);
p[rt].maxl=max(p[lrt].maxl,p[lrt].sum+p[rrt].maxl);
p[rt].maxr=max(p[rrt].maxr,p[rrt].sum+p[lrt].maxr);
}

void build(int l,int r,int rt){
if(l==r){
LL a;
scanf("%lld",&a);
p[rt]=(Node){a,a,a,a};
return;
}
middle;
build(lson);
build(rson);
pushup(rt);
}

Node query(int l,int r,int rt,int L,int R){
if(L<=l&&r<=R) return p[rt];
middle;
if(R<=m) return query(lson,L,R);
else if(L>m) return query(rson,L,R);
else{
Node x=query(lson,L,R);
Node y=query(rson,L,R);
Node ans;
ans.sum=x.sum+y.sum;
ans.maxv=max(max(x.maxv,y.maxv),x.maxr+y.maxl);
ans.maxl=max(x.maxl,x.sum+y.maxl);
ans.maxr=max(y.maxr,y.sum+x.maxr);
return ans;
}
}

int main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
build(1,n,1);
for(int i=2;i<=n;i++) a[i]+=a[i-1];
while(m--){
int aa,bb;
scanf("%d%d",&aa,&bb);
printf("%lld\n",query(1,n,1,aa,bb).maxv);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: