SPOJ GSS1 静态区间求解最大子段和

时间:2023-01-12 18:05:56

题目大意:

给定n个数,再给q个区间询问,希望在区间s,t中找到一段连续的子序列使其和最大

因为询问上万,节点数50000,明显是用线段树去做,这里很明显的区间更新,唯一写起来有点恶心的是询问

每一个区间的最大都要跟左右区间的左最大右最大有关系

反正时要注意细节了,查询的时候同时要查询其左右连续最大

自己的错误在于左右连续最大的更新出问题,这个希望自己以后要注意

 #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
using namespace std; const int INF = 0x3fffffff;
#define N 50010
#define MOD 100007
#define ls o<<1
#define rs o<<1|1
#define define_m int m=(l+r)>>1 int ml[N*] , mr[N*] , mx[N*] , sum[N*];
int a[N] , pre[N] , n; void push_up(int o)
{
mx[o] = max(mx[ls] , mx[rs]);
mx[o] = max(mx[o] , ml[rs]+mr[ls]);
ml[o] = max(ml[ls],sum[ls]+ml[rs]) , mr[o] = max(mr[rs],sum[rs]+mr[ls]);
sum[o] = sum[ls]+sum[rs];
} void build(int o , int l , int r)
{
if(l==r){
sum[o]=ml[o]=mr[o]=mx[o]=a[l];
return;
}
define_m;
build(ls , l , m);
build(rs , m+ , r);
push_up(o);
} void query(int o , int l , int r , int s , int t , int &ansl , int &ansr , int &ans)
{
if(l>=s && r<=t){
ans = mx[o];
ansl = ml[o];
ansr = mr[o];
return ;
}
define_m;
if(m>=t) query(ls , l , m , s , t , ansl , ansr , ans);
else if(m<s) query(rs , m+ , r , s , t , ansl , ansr ,ans);
else{
int t1,t2,t3,t4,t5,t6;
query(ls , l , m , s , m , t1 , t2 , t3);
query(rs , m+ , r , m+ , t , t4 , t5 , t6);
ansl = max(t1 , pre[m]-pre[s-]+t4) , ansr = max(t5 , pre[t]-pre[m]+t2);
ans = max(t3 , t6);
ans = max(ans , t2+t4);
}
//cout<<o<<" "<<l<<" "<<r<<" "<<s<<" "<<t<<" "<<ansl<<" "<<ansr<<" "<<ans<<endl;
} int main()
{
#ifndef ONLINE_JUDGE
freopen("a.in" , "r" , stdin);
#endif // ONLINE_JUDGE
while(~scanf("%d" , &n))
{
for(int i= ; i<=n ; i++){
scanf("%d" , a+i);
pre[i] = pre[i-]+a[i];
}
build( , , n);
int m;
scanf("%d" , &m);
for(int i= ; i<m ; i++){
int s , t;
scanf("%d%d" , &s , &t);
int t1,t2,t3;
query(,,n,s,t,t1,t2,t3);
printf("%d\n" , t3);
}
}
return ;
}