題目地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4595
大概題意:對區間進行一些小區間的增量操作,求最大值的最左端點和最右端點。
線段樹的結構設計如下:
struct node
{
int l; //區間右端點
int r; //區間左端點
int maxl; //區間最大值的最左端點
int maxr; //區間最大值的最右端點
int maxs; //區間最大值
int add; //記錄增量,用於懶操作
}T[maxn*4];
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 15005;
int maxs=0;
struct node
{
int l;
int r;
int maxl;
int maxr;
int maxs;
int add;
}T[maxn*4];
void Build(int t,int l,int r)
{
T[t].l=l;
T[t].r=r;
T[t].maxs=0;
T[t].add=0;
T[t].maxl=l;
T[t].maxr=r;
if(l<r)
{
int mid=(l+r)/2;
Build(2*t,l,mid);
Build(2*t+1,mid+1,r);
}
}
void Update(int t)
{
T[2*t].add+=T[t].add;
T[2*t].maxs+=T[t].add;
T[2*t+1].add+=T[t].add;
T[2*t+1].maxs+=T[t].add;
T[t].add=0;
}
void Insert(int t,int l,int r,int v)
{
if(T[t].l==l && T[t].r==r)
{
T[t].add+=v;
T[t].maxs+=v;
return ;
}
if(T[t].add!=0)
Update(t);
int mid=(T[t].l+T[t].r)/2;
if(r<=mid)
Insert(2*t,l,r,v);
else if(l>=mid+1)
Insert(2*t+1,l,r,v);
else
{
Insert(2*t,l,mid,v);
Insert(2*t+1,mid+1,r,v);
}
if(T[2*t].maxs==T[2*t+1].maxs)
{
T[t].maxs=T[2*t].maxs;
T[t].maxl=T[2*t].maxl;
T[t].maxr=T[2*t+1].maxr;
}
else if(T[2*t].maxs>T[2*t+1].maxs)
{
T[t].maxs=T[2*t].maxs;
T[t].maxl=T[2*t].maxl;
T[t].maxr=T[2*t].maxr;
}
else
{
T[t].maxs=T[2*t+1].maxs;
T[t].maxl=T[2*t+1].maxl;
T[t].maxr=T[2*t+1].maxr;
}
}
int main()
{
int n,a,b,c;
while(scanf("%d",&n)!=EOF)
{
maxs=0;
Build(1,0,n);
while(1)
{
scanf("%d %d %d",&a,&b,&c);
if(a==-1)
break;
Insert(1,a,b,c);
}
printf("%d %d\n",T[1].maxl,T[1].maxr);
}
return 0;
}