• 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;
    }
    
  • 相关阅读:
    Hdu 5256 系列转换
    SQL在declare声明变量
    煤火车问题
    百度音乐接口-——这可以基于在线音乐播放器来完成
    Android DrawerLayout 抽屉
    NETSH WINSOCK RESET这个命令的意义和效果?
    SSH三作品的框架和流程
    Solr入门指南
    客房收费制度的具体配置
    基本调试命令
  • 原文地址:https://www.cnblogs.com/acerkoo/p/12333542.html
Copyright © 2020-2023  润新知