Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

CF375D Tree and Queries

LuoGu: CF375D Tree and Queries

CF: D. Tree and Queries

dsu on tree ,树状数组维护每种颜色个数的个数的前缀和。

查看代码
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <cstdio>
#include <vector>
using namespace std;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
if (flag) x = ~x + 1;
}
template <class Type, class ...rest>
void read(Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write(Type x)
{
if (x < 0) putchar('-'), x = ~x + 1;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
const int N = 1e5 + 10;
int cnt[N], tr[N];
int n, m, w[N], p[N], sz[N], son[N], ans[N];
vector <int> g[N];
struct Query { int k, id; };
vector <Query> q[N];
void modify (int x, int k)
{
for (; x; x -= x & -x)
tr[x] += k;
}
int query (int x)
{
int res = 0;
for (; x <= n; x += x & -x)
res += tr[x];
return res;
}
void dfs1 (int x)
{
sz[x] = 1;
for (int i : g[x]) if (i ^ p[x])
{
p[i] = x;
dfs1(i);
sz[x] += sz[i];
if (sz[i] > sz[son[x]]) son[x] = i;
}
}
void update (int x, int op, int avoid)
{
modify(cnt[w[x]], -1), modify(cnt[w[x]] += op, 1);
for (int i : g[x]) if (i ^ avoid && i ^ p[x])
update(i, op, avoid);
}
void dfs2 (int x, int op)
{
for (int i : g[x]) if (i ^ son[x] && i ^ p[x])
dfs2(i, 0);
if (son[x]) dfs2(son[x], 1);
update(x, 1, son[x]);
for (Query i : q[x]) ans[i.id] = query(i.k);
if (!op) update(x, -1, 0);
}
int main ()
{
read(n, m);
for (int i = 1; i <= n; ++i) read(w[i]);
for (int i = 1, a, b; i < n; ++i)
{
read(a, b);
g[a].push_back(b), g[b].push_back(a);
}
for (int i = 1, u, k; i <= m; ++i)
{
read(u, k);
q[u].push_back((Query){k, i});
}
dfs1(1), dfs2(1, 0);
for (int i = 1; i <= m; ++i)
write(ans[i]), puts("");
return 0;
}