题意:
给出一棵
n
n
n个结点的树,每个结点有一个颜色
c
i
c_i
ci。询问
q
q
q次,每次询问以
v
v
v结点为根的子树中,出现次数
≥
k
≥k
≥k的颜色有多少种。树的根节点是
1
1
1。每次询问的
k
k
k不一定相同。
n
,
q
,
c
,
k
<
=
1
e
5
n,q,c,k<=1e5
n,q,c,k<=1e5。
题解:
好像我做了一天的水题啊。
子树问题肯定是先求dfs序,然后转化成序列问题。那么问题就变成了给你一个序列,有若干次询问,每次问你一个区间出现次数 > = k >=k >=k的值有多少个。一开始我有点傻,只会做 k k k都相同的。然后一想就发现,对于 1 − 1 e 5 1-1e5 1−1e5的每一个 k k k我们都记一下答案,每次修改一个值的时候只会改变其中一种情况的值。然后跑个莫队,就做完了。
复杂度 O ( n n ) O(n\sqrt{n}) O(nn)。
代码:
#include <bits/stdc++.h>
using namespace std;
int n,m,hed[200010],cnt,res[100010],ans[100010],c[100010],ji[200010];
int shu,fa[200010],xu[200010],ed[200010],sz,pos[200010],l=1,r,book[100010];
struct node
{
int to,next;
}a[400010];
struct qwq
{
int l,r,k,id;
}q[200010];
inline int read()
{
int x=0;
char s=getchar();
while(s>'9'||s<'0')
s=getchar();
while(s>='0'&&s<='9')
{
x=x*10+s-'0';
s=getchar();
}
return x;
}
inline void dfs(int x)
{
xu[x]=++shu;
ji[shu]=x;
for(int i=hed[x];i;i=a[i].next)
{
int y=a[i].to;
if(y==fa[x])
continue;
fa[y]=x;
dfs(y);
}
ed[x]=shu;
}
inline int cmp(qwq x,qwq y)
{
if(pos[x.l]!=pos[y.l])
return pos[x.l]<pos[y.l];
return x.r<y.r;
}
inline void ins(int from,int to)
{
a[++cnt].to=to;
a[cnt].next=hed[from];
hed[from]=cnt;
}
inline void add(int x)
{
++book[c[ji[x]]];
++res[book[c[ji[x]]]];
}
inline void del(int x)
{
--res[book[c[ji[x]]]];
--book[c[ji[x]]];
}
int main()
{
n=read();
m=read();
sz=sqrt(n);
for(int i=1;i<=n;++i)
{
c[i]=read();
pos[i]=(i-1)/sz+1;
}
for(int i=1;i<=n-1;++i)
{
int x=read(),y=read();
ins(x,y);
ins(y,x);
}
dfs(1);
for(int i=1;i<=m;++i)
{
q[i].l=read();
q[i].k=read();
q[i].r=ed[q[i].l];
q[i].l=xu[q[i].l];
q[i].id=i;
}
sort(q+1,q+m+1,cmp);
for(int i=1;i<=m;++i)
{
while(r<q[i].r)
add(++r);
while(r>q[i].r)
del(r--);
while(l<q[i].l)
del(l++);
while(l>q[i].l)
add(--l);
ans[q[i].id]=res[q[i].k];
}
for(int i=1;i<=m;++i)
printf("%d\n",ans[i]);
return 0;
}