- 「一本通 4.4 例 1」点的距离
你猜会不会AC?或WA?
- 2025-3-30 15:01:57 @
代码:
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const int MAXN = 1e5 + 5;
const int MAXLOG = 20;
vector<int> adj[MAXN];
int parent[MAXN], depth[MAXN];
int up[MAXLOG + 1][MAXN];
void bfs(int root) {
queue<int> q;
q.push(root);
parent[root] = 0;
depth[root] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (v != parent[u]) {
parent[v] = u;
depth[v] = depth[u] + 1;
q.push(v);
}
}
}
}
void preprocess(int n) {
for (int u = 1; u <= n; ++u) {
up[0][u] = parent[u];
}
for (int k = 1; k <= MAXLOG; ++k) {
for (int u = 1; u <= n; ++u) {
up[k][u] = up[k - 1][up[k - 1][u]];
}
}
}
int lca(int x, int y) {
if (depth[x] < depth[y]) {
swap(x, y);
}
int diff = depth[x] - depth[y];
for (int k = MAXLOG; k >= 0; --k) {
if (diff & (1 << k)) {
x = up[k][x];
}
}
if (x == y) {
return x;
}
for (int k = MAXLOG; k >= 0; --k) {
if (up[k][x] != up[k][y]) {
x = up[k][x];
y = up[k][y];
}
}
return up[0][x];
}
int distance(int x, int y) {
int lca_node = lca(x, y);
return depth[x] + depth[y] - 2 * depth[lca_node];
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n - 1; ++i) {
int x, y;
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
bfs(1);
preprocess(n);
int Q;
cin >> Q;
for (int i = 0; i < Q; ++i) {
int x, y;
cin >> x >> y;
cout << distance(x, y) << endl;
}
return 0;
}
信息
- ID
- 1368
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 4
- 标签
- (无)
- 递交数
- 183
- 已通过
- 32
- 上传者