E. 1-Trees and Queries
一道憨憨的 Lca 模板题。
Code
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int anc[maxn][20], dep[maxn];
vector<int> g[maxn];
int n;
void dfs(int x, int fa = 0) {
for (int i = 1; ~anc[x][i-1] && ~anc[anc[x][i-1]][i-1]; ++i)
anc[x][i] = anc[anc[x][i-1]][i-1];
dep[x] = dep[fa] + 1;
for (auto v: g[x]) {
if (v == fa) continue;
anc[v][0] = x;
dfs(v, x);
}
}
int lca(int x, int y) {
if (dep[x] > dep[y]) swap(x, y);
for (int j = 19; j >= 0; --j) {
if (~anc[y][j] && dep[anc[y][j]] >= dep[x])
y = anc[y][j];
}
if (x == y) return x;
for (int j = 19; j >= 0; --j) {
if (anc[x][j] != anc[y][j]) {
x = anc[x][j];
y = anc[y][j];
}
}
return anc[x][0];
}
int main() {
memset(anc, -1, sizeof anc);
scanf("%d", &n);
for (int u, v, i = 1; i < n; ++i) {
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1);
int q;
scanf("%d", &q);
for (int x, y, a, b, k, i = 1; i <= q; ++i) {
scanf("%d%d%d%d%d", &x, &y, &a, &b, &k);
int ab = dep[a] + dep[b] - dep[lca(a, b)] * 2;
int ax = dep[a] + dep[x] - dep[lca(a, x)] * 2;
int ay = dep[a] + dep[y] - dep[lca(a, y)] * 2;
int bx = dep[b] + dep[x] - dep[lca(b, x)] * 2;
int by = dep[b] + dep[y] - dep[lca(b, y)] * 2;
if (k >= ab && (k - ab) % 2 == 0) {
puts("YES");
} else if (k >= (ax + by + 1) && (k - ax - by - 1) % 2 == 0) {
puts("YES");
} else if (k >= (ay + bx + 1) && (k - ay - bx - 1) % 2 == 0) {
puts("YES");
} else {
puts("NO");
}
}
return 0;
}