CF 375D Tree and Queries

题目描述

http://codeforces.com/problemset/problem/375/D

Solution

大于等于 $k$ 的颜色个数是可以拿一个数组维护的

所以可以直接 $dsu$

时间复杂度 $O(n\log n)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
#define maxn 100010
using namespace std;

int n, m, a[maxn];

struct Edge {
int to, next;
} e[maxn * 2]; int c1, head[maxn];
inline void add_edge(int u, int v) {
e[c1].to = v; e[c1].next = head[u]; head[u] = c1++;
}

int sz[maxn], son[maxn], in[maxn], bl[maxn], out[maxn];
void Dfs(int u, int fa) {
static int cnt = 0;
int Max = 0; sz[u] = 1; in[u] = ++cnt; bl[cnt] = u;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa) continue;
Dfs(v, u); sz[u] += sz[v];
if (sz[v] > Max) Max = sz[v], son[u] = v;
} out[u] = cnt;
}

int d[maxn], cnt[maxn];
void add(int u) {
for (int i = in[u], v = bl[i]; i <= out[u]; v = bl[++i])
++cnt[a[v]], ++d[cnt[a[v]]];
}

void del(int u) {
for (int i = in[u], v = bl[i]; i <= out[u]; v = bl[++i])
--d[cnt[a[v]]], --cnt[a[v]];
}

vector<pair<int, int>> A[maxn]; int ans[maxn];
void dfs(int u, int fa) {
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa || v == son[u]) continue;
dfs(v, u); del(v);
}
if (son[u]) dfs(son[u], u);
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa || v == son[u]) continue;
add(v);
}
++cnt[a[u]]; ++d[cnt[a[u]]];
for (auto t : A[u]) ans[t.second] += d[t.first];
}

int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i < n; ++i) {
int x, y; cin >> x >> y;
add_edge(x, y); add_edge(y, x);
} Dfs(1, 0);
for (int i = 1; i <= m; ++i) {
int x, y; cin >> x >> y;
A[x].emplace_back(y, i);
} dfs(1, 0);
for (int i = 1; i <= m; ++i) cout << ans[i] << "\n";
return 0;
}