Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Ancestor Relation

#include <bits/stdc++.h>
using namespace std;

class Tree {
  public:
    int n, timer;
    vector<vector<int>> adj;
    vector<int> tin, tout;

    Tree(int n) {
        this->n = n;
        adj.resize(n);
        tin.resize(n);
        tout.resize(n);
        timer = 0;
    }

  public:
    void dfs(int src, int par) {
        tin[src] = ++timer;
        for (auto child : adj[src]) {
            if (child != par) {
                dfs(child, src);
            }
        }
        tout[src] = ++timer;
    }
};

void solve() {
    int n;
    cin >> n;
    Tree t(n);
    for (int i = 0; i < n - 1; i++) {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        t.adj[x].push_back(y);
        t.adj[y].push_back(x);
    }
    t.dfs(0, -1);

    int q;
    cin >> q;
    for (int i = 0; i < q; i++) {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        // Is x an ancestor of y?
        if (t.tin[x] <= t.tin[y] && t.tout[x] >= t.tout[y]) {
            cout << "YES"
                 << "\n";
        } else {
            cout << "NO"
                 << "\n";
        }
    }
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        solve();
    }
    return 0;
}