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.

Example

Input:
3 
-1 2 3
1
1 2

Output:
2

思路:

最主要的是如何求最大区间和,在这里我在树里(结构体)设了lans(从最左边开始的最大和),rans(最右边),ans(整个区间的最大和)。

关键看pushup()以及query()中的else{},理解清楚了就会了。

#include<iostream>
using namespace std;
const int N=50000;
int n,m,x,y,ans;
int a[N+5];
struct tree
{
	int sum,lans,rans,ans;	
}t[N*4+5];
void pushup(int k)
{
	t[k].sum =t[k*2].sum +t[k*2+1].sum ;
	t[k].lans =max(t[k*2].lans ,t[k*2].sum +t[k*2+1].lans );
	t[k].rans =max(t[k*2+1].rans ,t[k*2+1].sum +t[k*2].rans );
	t[k].ans =max(max(t[k*2].ans ,t[k*2+1].ans ),t[k*2].rans +t[k*2+1].lans );  
}
void build(int k,int l,int r)
{
	if(l==r)
	{
		t[k].sum =t[k].ans =t[k].lans =t[k].rans =a[l];
		return;
	}
	int mid=(l+r)/2;
	build(k*2,l,mid);
	build(k*2+1,mid+1,r);
	pushup(k);
}
tree query(int k,int x,int y,int l,int r)
{
	if(l>=x&&r<=y)
		return t[k] ;
	int mid=(l+r)/2;
	if(y<=mid)
		return query(k*2,x,y,l,mid);
	else if(x>mid)
		return query(k*2+1,x,y,mid+1,r);
	else
	{
		tree left,right,re;
		left=query(k*2,x,y,l,mid);
		right=query(k*2+1,x,y,mid+1,r);
		re.sum =left.sum +right.sum ;
		re.lans =max(left.lans ,left.sum +right.lans );
		re.rans =max(right.rans ,right.sum +left.rans );
		re.ans =max(max(left.ans ,right.ans ),left.rans +right.lans );
		return re;
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	build(1,1,n); 
	scanf("%d",&m);
	while(m--)
	{
		scanf("%d %d",&x,&y);
		ans=query(1,x,y,1,n).ans ;
		printf("%d\n",ans);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TherAndI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值