#include<cstdio>
#include<cstring>
#include<cstdlib>
const int maxn = 500005;
typedef long long ll;
int n,m;
ll a[maxn],sum[maxn];
struct node
{
int x,y,pre,suf,dx,dy;
};
node tnode[maxn*2];
void Build(int o,int x,int y)
{
tnode[o].x=x;
tnode[o].y=y;
if(x==y)
{
tnode[o].pre=x;
tnode[o].suf=x;
tnode[o].dx=x;
tnode[o].dy=x;
}
else
{
int mid=(x+y)/2;
Build(o*2,x,mid);
Build(o*2+1,mid+1,y);
tnode[o].dx=tnode[o*2].dx;
tnode[o].dy=tnode[o*2].dy;
if(sum[tnode[o].dy]-sum[tnode[o].dx-1] < sum[tnode[o*2+1].pre]-sum[tnode[o*2].suf-1])
{
tnode[o].dx=tnode[o*2].suf;
tnode[o].dy=tnode[o*2+1].pre;
}
if(sum[tnode[o].dy]-sum[tnode[o].dx-1] < sum[tnode[o*2+1].dy]-sum[tnode[o*2+1].dx-1])
{
tnode[o].dx=tnode[o*2+1].dx;
tnode[o].dy=tnode[o*2+1].dy;
}
tnode[o].pre=tnode[o*2].pre;
if(sum[tnode[o].pre] < sum[tnode[o*2+1].pre])
{
tnode[o].pre=tnode[o*2+1].pre;
}
tnode[o].suf=tnode[o*2+1].suf;
if(sum[tnode[o*2].suf-1] <= sum[tnode[o].suf-1])
{
tnode[o].suf=tnode[o*2].suf;
}
}
}
node Query(int o,int l,int r)
{
if(l==tnode[o].x && r==tnode[o].y)
return tnode[o];
int mid=(tnode[o].x+tnode[o].y)/2;
if(r<=mid)
{
return Query(o*2,l,r);
}
else if(l>mid)
{
return Query(o*2+1,l,r);
}
else
{
node ans,t1,t2;
t1=Query(o*2,l,mid);
t2=Query(o*2+1,mid+1,r);
ans.dx=t1.dx;
ans.dy=t1.dy;
if(sum[ans.dy]-sum[ans.dx-1] < sum[t2.pre]-sum[t1.suf-1])
{
ans.dx=t1.suf;
ans.dy=t2.pre;
}
if(sum[ans.dy]-sum[ans.dx-1] < sum[t2.dy]-sum[t2.dx-1])
{
ans.dx=t2.dx;
ans.dy=t2.dy;
}
ans.pre=t1.pre;
if(sum[ans.pre] < sum[t2.pre])
{
ans.pre=t2.pre;
}
ans.suf=t2.suf;
if(sum[t1.suf-1]<=sum[ans.suf-1])
{
ans.suf=t1.suf;
}
return ans;
}
}
int main()
{
int kcase=1;
while(~scanf("%d %d",&n,&m))
{
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
sum[0]=0;
for(int i=1;i<=n;i++)
{
sum[i]=sum[i-1]+a[i];
}
Build(1,1,n);
printf("Case %d:\n",kcase++);
for(int i=0;i<m;i++)
{
int x,y;
scanf("%d %d",&x,&y);
node ans=Query(1,x,y);
printf("%d %d\n",ans.dx,ans.dy);
}
}
return 0;
}
LA 3938( 线段树)
最新推荐文章于 2018-08-28 01:09:00 发布