SPOJ GSS1 Can you answer these queries I

You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 ). A query is defined as follows:
Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }.
Given M queries, your program must output the results of these queries.

Input

  • The first line of the input file contains the integer N.
  • In the second line, N numbers follow.
  • The third line contains the integer M.
  • M lines follow, where line i contains 2 numbers xi and yi.

Output

Your program should output the results of the M queries, one query per line.



线段树,每个节点维护区间和sum,从左端开始的最大值lmax,从右边开始的最大值rmax,和整段的最大值max。

由子段向上推的关系式如下。

sum=l.sum+r.sum

lmax=max(l.lmax,l.sum+r.lmax)  【前者不超过中点,后者贯穿中点】

rmax=max(r.rmax,r.sum+l.rmax)  【同上】

max=max(l.max,r.max,l.rmax+r.lmax)  【两边自己的最大值,或者两边连起来的最大值】




#include<cstdio>
struct node
{
	int lch,rch,l,r,lmax,rmax,max,sum;
}t[200010];
struct ans
{
	int l,r,max,s;
};
int n,nn,a[50010];
int mx(int x,int y)
{
	return x>y?x:y;
}
void build(int p,int l,int r)
{
	t[p].l=l;
	t[p].r=r;
	if (l==r)
	{
		t[p].lmax=t[p].rmax=t[p].max=t[p].sum=a[l];
		return;
	}
	int mid=(t[p].l+t[p].r)/2;
	t[p].lch=++nn;
	build(nn,l,mid);
	t[p].rch=++nn;
	build(nn,mid+1,r);
	t[p].sum=t[t[p].lch].sum+t[t[p].rch].sum;
	t[p].lmax=mx(t[t[p].lch].lmax,t[t[p].lch].sum+t[t[p].rch].lmax);
	t[p].rmax=mx(t[t[p].rch].rmax,t[t[p].rch].sum+t[t[p].lch].rmax);
	t[p].max=mx(mx(t[t[p].lch].max,t[t[p].rch].max),t[t[p].lch].rmax+t[t[p].rch].lmax);
}
ans find(int p,int l,int r)
{
	ans al,ar,a;
	if (t[p].l==l&&t[p].r==r)
	{
		a.l=t[p].lmax;
		a.r=t[p].rmax;
		a.max=t[p].max;
		a.s=t[p].sum;
		return a;
	}
	int mid=(t[p].l+t[p].r)/2;
	if (r<=mid) return find(t[p].lch,l,r);
	if (l>=mid+1) return find(t[p].rch,l,r);
	al=find(t[p].lch,l,mid);
	ar=find(t[p].rch,mid+1,r);
	a.l=mx(al.l,al.s+ar.l);
	a.r=mx(ar.r,ar.s+al.r);
	a.s=al.s+ar.s;
	a.max=mx(mx(al.max,ar.max),al.r+ar.l);
	return a;
}
int main()
{
	int i,j,k,m,p,q,x,y,z;
	scanf("%d",&n);
	for (i=1;i<=n;i++)
	  scanf("%d",&a[i]);
	nn=1;
	build(1,1,n);
	scanf("%d",&m);
	for (i=1;i<=m;i++)
	{
		scanf("%d%d",&x,&y);
		printf("%d\n",find(1,x,y).max);
	}
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值