# BZOJ3631松鼠的新家

3631: [JLOI2014]松鼠的新家
Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 1152 Solved: 586
Description

Input

Output

Sample Input
5
1 4 5 3 2
1 2
2 4
2 3
4 5
Sample Output
1
2
1
2
1
HINT
2<= n <=300000

``````#include<cstdio>
#include<iostream>
using namespace std;
#define MAXN 300001
int n,cnt,sz,a[MAXN],h[MAXN],father[MAXN][19],pos[MAXN],belong[MAXN],deep[MAXN],size[MAXN],delta[MAXN<<2];
bool vis[MAXN];
struct data
{
int to,next;
}edge[MAXN<<1];
struct kx
{
int value;
}node[MAXN<<2];

{
int w=0,c=1; char ch=getchar();
while (ch<'0' || ch>'9')
{
if (ch=='-') c=-1;
ch=getchar();
}
while (ch>='0' && ch<='9')
w=w*10+ch-'0',ch=getchar();
return w*c;
}

void add(int u,int v)
{
cnt++,edge[cnt].next=h[u],h[u]=cnt,edge[cnt].to=v;
}

void dfs1(int x)
{
int i;
vis[x]=true,size[x]=1;
for (i=1;i<=18;i++)
{
if (deep[x]<(1<<i)) break;
father[x][i]=father[father[x][i-1]][i-1];
}
for (i=h[x];i;i=edge[i].next)
{
if (vis[edge[i].to]) continue;
deep[edge[i].to]=deep[x]+1,father[edge[i].to][0]=x;
dfs1(edge[i].to),size[x]+=size[edge[i].to];
}
}

void dfs2(int x,int chain)
{
int k=0,i;
pos[x]=++sz,belong[x]=chain;
for (i=h[x];i;i=edge[i].next)
if (deep[edge[i].to]>deep[x] && size[edge[i].to]>size[k])
k=edge[i].to;
if (!k) return;
dfs2(k,chain);
for (i=h[x];i;i=edge[i].next)
if (deep[edge[i].to]>deep[x] && k!=edge[i].to)
dfs2(edge[i].to,edge[i].to);
}

void build(int s,int l,int r)
{
if (l==r) return;
build(s*2,l,(l+r)/2),build(s*2+1,(l+r)/2+1,r);
}

void paint(int s,int z)
{
node[s].value+=z,delta[s]+=z;
}

void pushdown(int s)
{
paint(s*2,delta[s]),paint(s*2+1,delta[s]),delta[s]=0;
}

int query(int s,int l,int r,int x)
{
int mid=(l+r)/2;
if (l==r) return node[s].value;
pushdown(s);
if (x<=mid) return query(s*2,l,mid,x);
return query(s*2+1,mid+1,r,x);
}

void insert(int s,int l,int r,int x,int y,int z)
{
int mid=(l+r)/2;
if (l==x && y==r)
{
paint(s,z);
return;
}
pushdown(s);
if (y<=mid) insert(s*2,l,mid,x,y,z);
else if (x>mid) insert(s*2+1,mid+1,r,x,y,z);
else insert(s*2,l,mid,x,mid,z),insert(s*2+1,mid+1,r,mid+1,y,z);
}

void solveinsert(int x,int y,int z)
{
for (;belong[x]!=belong[y];x=father[belong[x]][0])
{
if (deep[belong[x]]<deep[belong[y]]) swap(x,y);
insert(1,1,n,pos[belong[x]],pos[x],z);
}
if (deep[x]<deep[y]) swap(x,y);
insert(1,1,n,pos[y],pos[x],z);
}

int main()
{
int i,x,y;