题解:AT_abc414_f [ABC414F] Jump Traveling
WilliamFranklin · · 题解
Solution
一个很自然的想法是直接 bfs,但是我们发现 bfs 是,虽然一个点只会被加入一次,但是一个点被判断是否被遍历过的次数是可能是非常多的,所以我们考虑优化。
先以
并且考虑,最终
这样对于每个点只会被最多判断两次,时间复杂度为
感觉说起来有点模糊,但是代码很清晰。
AC Code
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp(Tx, Ty) make_pair(Tx, Ty)
#define For(Ti, Ta, Tb) for(auto Ti = (Ta); Ti <= (Tb); Ti++)
#define Dec(Ti, Ta, Tb) for(auto Ti = (Ta); Ti >= (Tb); Ti--)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define range(Tx) begin(Tx),end(Tx)
const int N = 2e5 + 5;
int n, K;
int h[N], e[N * 2], ne[N * 2], idx;
vector<int> G[N][21];
int l[N][21], r[N][21];
int dfn[N], dfncnt, sz[N], f[N], son[N], dep[N], top[N];
int dist[N];
bool vis[N];
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int x, int fa) {
f[x] = fa, dep[x] = dep[fa] + 1, sz[x] = 1, dfn[x] = ++dfncnt;
for (int i = h[x]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
dfs(j, x);
sz[x] += sz[j];
if (sz[son[x]] < sz[j]) son[x] = j;
For(k, 0, K - 1) for (auto l : G[j][k]) G[x][k + 1].push_back(l), r[x][k + 1]++;
}
G[x][0].push_back(x), r[x][0] = 1;
}
void dfs1(int x, int fa, int t) {
top[x] = t;
if (son[x]) dfs1(son[x], x, t);
for (int i = h[x]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
if (j == son[x]) continue;
dfs1(j, x, j);
}
}
int lca(int x, int y) {
while (top[x] != top[y]) {
if (dep[top[x]] > dep[top[y]]) x = f[top[x]];
else y = f[top[y]];
}
if (dep[x] > dep[y]) return y;
return x;
}
int get_dist(int x, int y) {
int sfa = lca(x, y);
return dep[x] + dep[y] - 2 * dep[sfa];
}
void bfs() {
queue<int> q;
q.push(1), dist[1] = 0, vis[1] = 1;
while (q.size()) {
int t = q.front();
q.pop();
int now = t, cnt = 0;
while (now != 0 && cnt <= K) {
while (r[now][K - cnt] - l[now][K - cnt] + 1 > 0) {
int i = G[now][K - cnt][r[now][K - cnt]];
if (vis[i]) {
r[now][K - cnt]--;
continue;
}
if (get_dist(i, t) != K) break;
else dist[i] = dist[t] + 1, q.push(i), vis[i] = 1, r[now][K - cnt]--;
}
while (r[now][K - cnt] - l[now][K - cnt] + 1 > 0) {
int i = G[now][K - cnt][l[now][K - cnt]];
if (vis[i]) {
l[now][K - cnt]++;
continue;
}
if (get_dist(i, t) != K) break;
else dist[i] = dist[t] + 1, q.push(i), vis[i] = 1, l[now][K - cnt]++;
}
cnt++;
now = f[now];
}
}
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int T;
cin >> T;
while (T--) {
cin >> n >> K;
For(i, 1, n) h[i] = -1;
For(i, 1, n) For(j, 0, K) G[i][j].clear(), l[i][j] = 0, r[i][j] = -1;
For(i, 1, n) vis[i] = son[i] = top[i] = dep[i] = 0, dist[i] = -1;
dep[0] = -1, idx = 0, dfncnt = 0;
For(i, 1, n - 1) {
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
dfs(1, 0), dfs1(1, 0, 1);
bfs();
For(i, 2, n) cout << dist[i] << " \n"[i == n];
}
return 0;
}