题意:
思路: 很明显子树问题会想到树启,让后如何
u
p
d
a
t
e
update
update呢?一个显然的思路就是维护一个树状数组,查询次数
>
=
k
j
>=k_j
>=kj的个数。但是这样复杂度是
O
(
n
l
o
g
2
n
)
O(nlog^2n)
O(nlog2n)的,有没有更优的方式呢?注意到我们可以维护一个出现次数的前缀和,记数组
c
n
t
[
i
]
cnt[i]
cnt[i]为出现次数为
i
i
i的颜色个数,
c
[
i
]
c[i]
c[i]为
i
i
i颜色出现的次数,当前颜色为
c
o
l
col
col。每次更新的时候,比如说现在
t
a
g
tag
tag为
1
1
1,按正常的思路应该是
c
[
c
o
l
]
+
+
,
c
n
t
[
c
[
c
o
l
]
−
1
]
−
−
,
c
n
t
[
c
[
c
o
l
]
]
+
+
c[col]++,cnt[c[col]-1]--,cnt[c[col]]++
c[col]++,cnt[c[col]−1]−−,cnt[c[col]]++。这样写的话,就需要用树状数组查询一下
>
=
k
>=k
>=k的个数了,但是我们修改一下
c
n
t
[
i
]
cnt[i]
cnt[i]的含义,改成出现次数
>
=
i
>=i
>=i的颜色个数(我语文不好,别打脸),这样修改的时候只需要
c
[
c
o
l
]
+
+
,
c
n
t
[
c
[
c
o
l
]
]
+
+
c[col]++,cnt[c[col]]++
c[col]++,cnt[c[col]]++,这样更新的时候答案就是
c
n
t
[
k
]
cnt[k]
cnt[k]了。
复杂度
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)。
如果改成出现次数
<
k
j
<k_j
<kj的颜色个数,我们只需要再维护一下子树中颜色的个数
s
u
m
sum
sum,那么
a
n
s
=
s
u
m
−
c
n
t
[
k
j
]
ans=sum-cnt[k_j]
ans=sum−cnt[kj]。
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;
//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;
int n,m;
int col[N],se[N],son[N];
int cnt[N],c[N],ans[N];
vector<int>v[N];
vector<PII>query[N];
void dfs_son(int u,int f)
{
se[u]=1;
for(auto x:v[u]) if(x!=f) { dfs_son(x,u); se[u]+=se[x]; if(se[x]>se[son[u]]) son[u]=x; }
}
void update(int u,int f,int tag,int p)
{
if(tag==1) c[col[u]]++,cnt[c[col[u]]]++;
else c[col[u]]--,cnt[c[col[u]]+1]--;
for(auto x:v[u]) if(x!=f&&x!=p) update(x,u,tag,p);
}
void dfs(int u,int f,int op)
{
for(auto x:v[u]) if(x!=f&&x!=son[u]) dfs(x,u,0);
if(son[u]) dfs(son[u],u,1);
update(u,f,1,son[u]);
for(int i=0;i<query[u].size();i++) ans[query[u][i].X]=cnt[query[u][i].Y];
if(!op) update(u,f,-1,0);
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&col[i]);
for(int i=1;i<=n-1;i++)
{
int a,b; scanf("%d%d",&a,&b);
v[a].pb(b); v[b].pb(a);
}
for(int i=1;i<=m;i++)
{
int v,k; scanf("%d%d",&v,&k);
query[v].pb({i,k});
}
dfs_son(1,0); dfs(1,0,0);
for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
return 0;
}
/*
*/