题目链接
树剖本蒻苟一知没敢学,最后集训题目集出了这个题目,所以以此题学一下。
学懂后觉得不难,本人理解树链剖分本质上其实还是线段树,只不过通过对轻重链的划分,让树上节点连续化,以保留树上信息。从而使对树上链状的节点的修改连续化,使区间维护成为可能。可以去大佬博客学一下。
#include
#include
#include
#include
#include
#include
using namespace std;
const int N = 1e6+50;
int dep[N], siz[N], fa[N], id[N], son[N], top[N];
int dfn[N], w[N];
int ver[N<<1], ne[N<<1], he[N];
int tot;
struct Node
{
int l, r, val, add;
}tr[N<<1];
void add(int x, int y)
{
ne[++tot] = he[x];
ver[tot] = y;
he[x] = tot;
}
void dfs1(int u, int f)
{
fa[u] = f;
dep[u] = dep[f]+1;
siz[u] = 1;
int mx = -1;
for (int i = he[u]; i; i = ne[i])
{
int y = ver[i];
if (y == f) continue;
dfs1(y, u);
siz[u] += siz[y];
if (siz[y] > mx)
{
mx = siz[y];
son[u] = y;
}
}
}
int cnt;
void dfs2(int u, int t)
{
dfn[u] = ++cnt;
top[u] = t;
w[cnt] = 0;
if (!son[u])
return;
dfs2(son[u], t);
for (int i = he[u]; i; i = ne[i])
{
int v = ver[i];
if (v == fa[u] || v == son[u])
continue;
dfs2(v, v);
}
}
void build(int p, int l, int r)
{
tr[p].val = 0;
tr[p].add = -1;
tr[p].l = l; tr[p].r = r;
if (l == r)
return;
int mid = (l + r) >> 1;
build(p<<1, l, mid);
build(p<<1|1, mid+1, r);
}
void spread(int p)
{
if (tr[p].add == -1) return;
int l = p<<1, r = p<<1|1;
tr[l].val = tr[p].add;
tr[r].val = tr[p].add;
tr[l].add = tr[r].add = tr[p].add;
tr[p].add = -1;
}
int ask(int p, int k)
{
if (tr[p].l == tr[p].r) return tr[p].val;
spread(p);
int mid = (tr[p].l+tr[p].r) >> 1;
if (k <= mid) return ask(p<<1, k);
else return ask(p<<1|1, k);
}
void change(int p, int l, int r, int v)
{
if (l <= tr[p].l && tr[p].r <= r)
{
tr[p].val = v;
tr[p].add = v;
return;
}
spread(p);
int mid = (tr[p].l + tr[p].r) >> 1;
if (l <= mid) change(p<<1, l, r, v);
if (r > mid) change(p<<1|1, l, r, v);
}
inline void cha(int x, int z)
{
change(1, dfn[x], dfn[x]+siz[x]-1, z);
}
inline int qu(int x)
{
return ask(1, dfn[x]);
}
void mc(int x, int z)
{
int y = 1;
while(top[x] != top[y])
{
if (dep[top[x]] < dep[top[y]])
swap(x, y);
change(1, dfn[top[x]], dfn[x], z);
x = fa[top[x]];
}
if (dep[x] > dep[y])
swap(x, y);
change(1, dfn[x], dfn[y], z);
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i < n; i++)
{
int x, y;
scanf("%d%d", &x, &y);
add(x, y);
add(y, x);
}
dfs1(1, 0);
dfs2(1, 0);
build(1, 1, n);
int q;
scanf("%d", &q);
while(q--)
{
int op;
scanf("%d", &op);
if (op ==1)
{
int k;
scanf("%d", &k);
cha(k, 1);
}
else if (op == 2)
{
int k;
scanf("%d", &k);
mc(k, 0);
}
else
{
int k;
scanf("%d", &k);
printf("%d\n", qu(k));
}
}
return 0;
}