题解:树链剖分
小水题,不解释。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 1000003
using namespace std;
int n,m,tot,l[N],r[N],point[N],nxt[N],v[N],sz;
int fa[N],deep[N],size[N],son[N],pos[N],belong[N],tr[N*4],delta[N*4];
void add(int x,int y)
{
tot++; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;
tot++; nxt[tot]=point[y]; point[y]=tot; v[tot]=x;
}
void dfs(int x,int f)
{
size[x]=1; deep[x]=deep[f]+1;
for (int i=point[x];i;i=nxt[i]) {
if (v[i]==f) continue;
fa[v[i]]=x;
dfs(v[i],x);
size[x]+=size[v[i]];
if (size[v[i]]>size[son[x]]) son[x]=v[i];
}
}
void dfs1(int x,int chain)
{
belong[x]=chain; pos[x]=++sz; l[x]=r[x]=sz;
if (!son[x]) return ;
dfs1(son[x],chain);
for (int i=point[x];i;i=nxt[i])
if(v[i]!=fa[x]&&v[i]!=son[x]) dfs1(v[i],v[i]);
r[x]=sz;
}
void pushdown(int now)
{
if (delta[now]!=-1) {
delta[now<<1]=delta[now];
delta[now<<1|1]=delta[now];
tr[now<<1]=delta[now]; tr[now<<1|1]=delta[now];
delta[now]=-1;
}
}
void qjchange(int now,int l,int r,int ll,int rr,int val)
{
if (ll<=l&&r<=rr) {
tr[now]=val;
delta[now]=val;
return;
}
int mid=(l+r)/2;
pushdown(now);
if (ll<=mid) qjchange(now<<1,l,mid,ll,rr,val);
if (rr>mid) qjchange(now<<1|1,mid+1,r,ll,rr,val);
}
int find(int now,int l,int r,int x)
{
if (l==r) return tr[now];
int mid=(l+r)/2;
pushdown(now);
if (x<=mid) return find(now<<1,l,mid,x);
else return find(now<<1|1,mid+1,r,x);
}
void solve(int x,int y)
{
while (belong[x]!=belong[y]){
if (deep[belong[x]]<deep[belong[y]]) swap(x,y);
qjchange(1,1,n,pos[belong[x]],pos[x],0);
x=fa[belong[x]];
}
if (deep[x]>deep[y]) swap(x,y);
qjchange(1,1,n,pos[x],pos[y],0);
}
int main()
{
freopen("a.in","r",stdin);
scanf("%d",&n);
for (int i=1;i<n;i++) {
int x,y; scanf("%d%d",&x,&y);
add(x,y);
}
dfs(1,0); dfs1(1,1);
memset(delta,-1,sizeof(delta));
scanf("%d",&m);
for (int i=1;i<=m;i++) {
int opt,x; scanf("%d%d",&opt,&x);
if (opt==1) qjchange(1,1,n,l[x],r[x],1);
if (opt==2) solve(1,x);
if (opt==3) printf("%d\n",find(1,1,n,pos[x]));
}
}