题解:AT_past201912_k 巨大企業

· · 题解

题目分析

题目中说明有 n 个点,编号为 1 到 n,在输入中,给出了编号为 i 的点连出的有向边连向的点的编号。\ 注意到这里:

不存在重边和自环,也不存在一个点,使得从该点出发,沿着有向边走,能够回到这个点

所以,我们可以把这个图看成一棵树,只是这棵树是由有向边联通的。\ 此时,如果有一个点连接的点的编号为 -1,就说明这个点为根节点。\ 题目中要判断从 a_i 出发能否到达 b_i,即两个点是否有公共祖先。

AC Code:

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
int n,q,s;
int f[N][20], depth[N];
int tot, lg[N];
int head[N]; 
struct node {
    int u, v, nxt;
}e[N << 1];
void add(int u,int v) {
    ++tot;
    e[tot] = {u, v, head[u]};
    head[u] = tot;
}
void dfs(int now, int fa) {
    depth[now] = depth[fa] + 1;
    f[now][0] = fa;
    for(int i = head[now]; i; i = e[i].nxt) {
        if(e[i].v != fa) dfs(e[i].v, now);
    }
}
int lca(int x, int y) {
    if(depth[x] < depth[y]) swap(x, y);
    while(depth[x] > depth[y]) {
        int c = depth[x] - depth[y];
        x = f[x][lg[c]];
    }
    if(x == y) return x;
    for(int i=18; i>=0; i--) {
        if(f[x][i] != f[y][i]) {
            x = f[x][i];
            y = f[y][i];
        }
    }
    return f[x][0];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n;
    for(int i=2; i<=n; i++) lg[i] = lg[i / 2] + 1;
    for(int i=1; i<=n; i++) {
        int edge;
        cin >> edge;
        if(edge == -1) s = i;
        else add(edge, i);
    }
    dfs(s, 0);
    for(int j=1; j<=18; j++)
        for(int i=1; i<=n; i++)
            f[i][j] = f[f[i][j - 1]][j - 1];
    cin >> q;
    while(q--) {
        int a, b;
        cin>> a >> b;
        if(lca(a, b) == b) cout << "Yes" << '\n';
        else cout << "No" << '\n';
    }
    return 0;
}