Blog of RuSun

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

CF208E Blood Cousins

LuoGu: CF208E Blood Cousins

CF: E. Blood Cousins

求 $k$ 级祖先的 $k$ 级儿子,$k$ 级祖先用重链剖分求(实际上用栈 $O(n)$ 预处理),$k$ 级儿子离线后长链剖分求。

还可以线段树合并,dsu on tree 。

另有加强版 P5384,卡空间,放弃重剖,将 vector 改为邻接表。

查看代码
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#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;
vector <int> g[N];
int n, m, p[N], ans[N];
struct Query
{
int k, id;
};
vector <Query> q[N];
namespace Heavy
{
int stmp, d[N], sz[N], son[N], top[N], dfn[N], rnk[N];
void dfs1 (int x)
{
sz[x] = 1;
for (int i : g[x])
{
d[i] = d[x] + 1;
dfs1(i);
sz[x] += sz[i];
if (sz[i] > sz[son[x]]) son[x] = i;
}
}
void dfs2 (int x, int t)
{
top[x] = t;
rnk[dfn[x] = ++stmp] = x;
if (!son[x]) return;
dfs2(son[x], t);
for (int i : g[x]) if (i ^ son[x])
dfs2(i, i);
}
int kth (int x, int k)
{
while (d[x] - d[p[top[x]]] <= k)
{
k -= d[x] - d[p[top[x]]];
x = p[top[x]];
}
return rnk[dfn[x] - k];
}
void main ()
{
for (int i = 1; i <= n; ++i) if (!p[i])
d[i] = 1, dfs1(i), dfs2(i, i);
}
}
namespace Long
{
int d[N], son[N], v[N], *f[N], *cur = v;
void dfs1 (int x)
{
for (int i : g[x])
{
dfs1(i);
if (d[i] > d[son[x]]) son[x] = i;
}
d[x] = d[son[x]] + 1;
}
void dfs2 (int x)
{
f[x][0] = 1;
if (son[x]) f[son[x]] = f[x] + 1, dfs2(son[x]);
for (int i : g[x]) if (i ^ son[x])
{
f[i] = cur, cur += d[i], dfs2(i);
for (int k = 1; k <= d[i]; ++k)
f[x][k] += f[i][k - 1];
}
for (Query i : q[x])
ans[i.id] = f[x][i.k] - 1;
}
void main ()
{
for (int i = 1; i <= n; ++i) if (!p[i])
{
dfs1(i);
f[i] = cur, cur += d[i], dfs2(i);
}
}
}
int main ()
{
read(n);
for (int i = 1; i <= n; ++i)
{
read(p[i]);
if (p[i]) g[p[i]].push_back(i);
}
Heavy::main();
read(m);
for (int i = 1, t, k; i <= m; ++i)
{
read(t, k);
if (Heavy::d[t] > k)
q[Heavy::kth(t, k)].push_back((Query){k, i});
}
Long::main();
for (int i = 1; i <= m; ++i)
write(ans[i]), putchar(' ');
return 0;
}