码迷,mamicode.com
首页 > 其他好文 > 详细

E. 1-Trees and Queries

时间:2020-02-19 22:25:52      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:back   lse   cto   return   eof   int   mem   auto   code   

传送门

一道憨憨的 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;
}

E. 1-Trees and Queries

标签:back   lse   cto   return   eof   int   mem   auto   code   

原文地址:https://www.cnblogs.com/acerkoo/p/12333542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!