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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章