GSS1 - Can you answer these queries I(动态查询区间最大连续和)

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.

这个题目可以用线段树去做,一个可行的思路就是计算出三个标记mc[](当前区间内最大的连续子串和),lc[](从当前区间左端点开始向右的最大的连续子串和),rc[](从当前区间右端点开始的向左的最大的连续子串和)。

查询的时候利用这三个标记进行计算就可以了。

#include<bits/stdc++.h>
#define MAXN 50010
using namespace std;
int lc[4*MAXN],rc[4*MAXN],mc[4*MAXN];
int prefix[MAXN];
void build(int id,int l,int r)
{
	if(l==r)
	{
		mc[id]=lc[id]=rc[id]=prefix[l]-prefix[l-1];
		return;
	}
	int mid=(l+r)/2;
	build(id*2,l,mid);
	build(id*2+1,mid+1,r);
	lc[id]=max(lc[id*2],prefix[mid]-prefix[l-1]+lc[id*2+1]);
	rc[id]=max(rc[id*2+1],prefix[r]-prefix[mid]+rc[id*2]);
	mc[id]=max(max(mc[id*2],mc[id*2+1]),rc[id*2]+lc[id*2+1]);
}
int query(int id,int x,int y,int l,int r,int flag,int &ans)
{
	if(l<=x&&y<=r)
	{
		ans=max(ans,mc[id]);
		return flag==-1?lc[id]:rc[id];
	}
	int mid=(x+y)/2;
	if(r<=mid)
	return query(id*2,x,mid,l,r,-1,ans);
	else if(l>mid)
	return query(id*2+1,mid+1,y,l,r,1,ans);
	else
	{
		int ln=query(id*2,x,mid,l,r,1,ans);
		int rn=query(id*2+1,mid+1,y,l,r,-1,ans);
		ans=max(ln+rn,ans);
		if(flag==-1)
		return max(lc[id*2],prefix[mid]-prefix[x-1]+rn);
		else
		return max(rc[id*2+1],prefix[y]-prefix[mid]+ln);
	}
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		prefix[0]=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&prefix[i]);
        prefix[i]+=prefix[i-1];
    }
   	build(1,1,n);
   	int m;
   	scanf("%d",&m);
   	for(int i=0;i<m;i++)
   	{
   		int l,r;
   		scanf("%d%d",&l,&r);
   		int ans=prefix[l]-prefix[l-1];
   		query(1,1,n,l,r,-1,ans);
   		printf("%d\n",ans);
	}
	}
	
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值