传送门
嗯,一道裸裸的树剖。
代码:
#include
#include
using namespace std;
const int Maxn=30005;
const int oo=2147483647;
struct segment{int v,next;}e[Maxn*2];
struct Qtree{int l,r,mx,sum;}t[Maxn*4];
int size[Maxn],pos[Maxn],head[Maxn],fa[Maxn],depth[Maxn],w[Maxn],top[Maxn];
int cnt,tmp,n,q;
void insert(int u,int v)
{
e[++cnt].v=v;e[cnt].next=head[u];head[u]=cnt;
e[++cnt].v=u;e[cnt].next=head[v];head[v]=cnt;
}
void dfs1(int x)
{
size[x]=1;
for(int i=head[x];i;i=e[i].next)
{
if(e[i].v==fa[x])continue;
depth[e[i].v]=depth[x]+1;
fa[e[i].v]=x;
dfs1(e[i].v);
size[x]+=size[e[i].v];
}
}
void dfs2(int x,int tp)
{
int k=0;
pos[x]=++tmp;;
top[x]=tp;
for(int i=head[x];i;i=e[i].next)
if(depth[e[i].v]>depth[x]&&size[e[i].v]>size[k])
k=e[i].v;
if(k==0)return ;
dfs2(k,tp);
for(int i=head[x];i;i=e[i].next)
if(depth[e[i].v]>depth[x]&&e[i].v!=k)
dfs2(e[i].v,e[i].v);
}
void build(int l,int r,int rt)
{
t[rt].l=l;t[rt].r=r;
if(l==r)return ;
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
}
int Qsum(int lf,int rf,int rt)
{
int l=t[rt].l,r=t[rt].r,mid=(l+r)>>1,sum=0;
if(l>=lf&&r<=rf)return t[rt].sum;
if(lf<=mid)sum+=Qsum(lf,rf,rt<<1);
if(rf>mid)sum+=Qsum(lf,rf,rt<<1|1);
//t[rt].sum=t[rt<<1].sum+t[rt<<1|1].sum;
return sum;
}
int Qmax(int lf,int rf,int rt)
{
int l=t[rt].l,r=t[rt].r,mid=(l+r)>>1,maxp=-oo;
if(l>=lf&&r<=rf)return t[rt].mx;
if(lf<=mid)maxp=max(maxp,Qmax(lf,rf,rt<<1));
if(rf>mid)maxp=max(maxp,Qmax(lf,rf,rt<<1|1));
//t[rt].mx=max(t[rt<<1].mx,t[rt<<1|1].mx);
return maxp;
}
void change(int x,int d,int rt)
{
int l=t[rt].l,r=t[rt].r,mid=(l+r)>>1;
if(l==r){t[rt].sum=t[rt].mx=d;return;}
if(x<=mid)change(x,d,rt<<1);
else change(x,d,rt<<1|1);
t[rt].sum=t[rt<<1].sum+t[rt<<1|1].sum;
t[rt].mx=max(t[rt<<1].mx,t[rt<<1|1].mx);
}
int solvesum(int lf,int rf)
{
int sum=0;
while(top[lf]!=top[rf])
{
if(depth[top[lf]]pos[rf])swap(lf,rf);
sum+=Qsum(pos[lf],pos[rf],1);
return sum;
}
int solvemax(int lf,int rf)
{
int maxp=-oo;
while(top[lf]!=top[rf])
{
if(depth[top[lf]]pos[rf])swap(lf,rf);
maxp=max(maxp,Qmax(pos[lf],pos[rf],1));
return maxp;
}
int main()
{
scanf("%d",&n);
for(int i=1;i