链接
https://codeforces.com/contest/246/problem/E
题解
d
s
u
o
n
t
r
e
e
dsu\ on\ tree
dsu on tree裸题,想一下怎么暴力:直接遍历子树,每个深度维护一个
s
e
t
set
set,查询的时候去对应的深度求
s
e
t
set
set的大小就行了
删除的时候就直接去
s
e
t
set
set里
e
r
a
s
e
erase
erase
代码
#include <bits/stdc++.h>
#define maxn 100010
#define maxe 200010
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
struct Trie
{
int trie[maxn*20][28], tot, tail[maxn*20];
void clear() //clear the arrays
{
for(int i=1;i<=tot;i++)cl(trie[i]), tail[i]=0;
tot=1;
}
int insert(int *r, int len) //insert a string into trie tree
{
auto pos=1;
for(auto i=1;i<=len;i++)
pos = trie[pos][r[i]] ? trie[pos][r[i]] : trie[pos][r[i]]=++tot;
tail[pos]++;
return pos;
}
}trie;
struct Graph
{
int etot, head[maxn], to[maxe], next[maxe], w[maxe];
void clear(int N)
{
for(int i=1;i<=N;i++)head[i]=0;
etot=0;
}
void adde(int a, int b, int c){to[++etot]=b;w[etot]=c;next[etot]=head[a];head[a]=etot;}
}G;
struct ShuLianPouFen
{
int size[maxn], top[maxn], tid[maxn], tim, untid[maxn], deep[maxn], son[maxn], fa[maxn];
void dfs1(Graph &G, int pos)
{
int p, v;
size[pos]=1;
for(p=G.head[pos];p;p=G.next[p])
{
if((v=G.to[p])==fa[pos])continue;
fa[v]=pos;
deep[v]=deep[pos]+1;
dfs1(G,v);
if(size[v]>size[son[pos]])son[pos]=v;
size[pos]+=size[v];
}
}
void dfs2(Graph &G, int pos, int tp)
{
int p, v;
top[pos]=tp;
tid[pos]=++tim;
untid[tid[pos]]=pos;
if(son[pos])dfs2(G,son[pos],tp);
for(p=G.head[pos];p;p=G.next[p])
if((v=G.to[p])!=fa[pos] and v!=son[pos])dfs2(G,v,v);
}
void run(Graph &G, int root)
{
tim=0;
dfs1(G,root);
dfs2(G,root,root);
}
}SP;
int n, m, k[maxn], ans[maxn], col[maxn], forb, f[maxn];
vector<int> qlis[maxn];
set<int> s[maxn];
void force(int pos, int pre, int opt)
{
if(opt==1)s[SP.deep[pos]].emplace(col[pos]);
else s[SP.deep[pos]].erase(col[pos]);
for(auto p=G.head[pos];p;p=G.next[p])
if(G.to[p]!=pre and G.to[p]!=forb)
force(G.to[p],pos,opt);
}
void dfs(int pos, int pre, int H)
{
for(auto p=G.head[pos];p;p=G.next[p])
if(G.to[p]!=pre and G.to[p]!=SP.son[pos])
dfs(G.to[p],pos,0);
if(SP.son[pos])dfs(SP.son[pos],pos,1);
forb=SP.son[pos];
force(pos,pre,1);
for(auto q:qlis[pos])
{
if(SP.deep[pos]+k[q]<=n)ans[q]=s[SP.deep[pos]+k[q]].size();
}
if(H==0)forb=0, force(pos,pre,-1);
}
int main()
{
char s[50];
int r[50], i;
scanf("%d",&n);
trie.clear();
for(i=1;i<=n;i++)
{
scanf("%s%d",s+1,f+i);
if(f[i]==0)f[i]=n+1;
G.adde(i,f[i],0), G.adde(f[i],i,0);
auto len=strlen(s+1);
for(int j=1;j<=len;j++)r[j]=s[j]-'a'+1;
col[i]=trie.insert(r,len);
}
SP.run(G,n+1);
scanf("%d",&m);
for(i=1;i<=m;i++)
{
int v;
scanf("%d%d",&v,k+i);
qlis[v].emplace_back(i);
}
dfs(n+1,0,0);
for(i=1;i<=m;i++)printf("%d\n",ans[i]);
return 0;
}