Saturday, December 23, 2023

[Hackerearth] BanquetSplit

 

Problem Link    : BanquetSplit
Category        : Graph, Lowest Common Ancestor
Contest         : December Circuits'23  
#include "bits/stdc++.h"
using namespace std;
#define int     long long int
#define endl    '\n'
 
const int maxn = 1e6 + 5;
const int logn = 21;
 
int n;
vector<vector<int>> graph;
int depth[maxn];
int father[maxn][logn];
 
void init(int n) {
    graph.clear(); graph.resize(n + 1);
    for (int i = 0; i <= n; i++) {
        depth[i] = 0;
        memset(father[i], 0, sizeof father[i]);
    }
}
 
void dfs(int u, int p, int lvl) {
    depth[u] = lvl;
    father[u][0] = p;
    for (int i = 1; i < logn; i++) {
        father[u][i] = father[ father[u][i - 1] ][i - 1];
    }
    for (int v : graph[u]) {
        if (v == p) {
            continue;
        }
        dfs(v, u, lvl + 1);
    }
}
 
int findLca(int u, int v) {
    if (depth[u] < depth[v]) {
        swap(u, v);
    }
    for (int i = logn - 1; i >= 0; i--) {
        if (depth[ father[u][i] ] >= depth[v]) {
            u = father[u][i];
        }
    }
    if (u == v) {
        return u;
    }
    for (int i = logn - 1; i >= 0; i--) {
        if (father[u][i] != father[v][i]) {
            u = father[u][i];
            v = father[v][i];
        }
    }
    return father[u][0];
}
 
void solve() {
    cin >> n;
    init(n);
    for (int e = 1; e < n; e++) {
        int u, v;
        cin >> u >> v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    dfs(1, 0, 1);
    int q;
    cin >> q;
    while (q--) {
        int x, y;
        cin >> x >> y;
        int lca = findLca(x, y);
        int dist = depth[x] + depth[y] - 2 * depth[lca];
        if (dist & 1) {
            cout << "Yes" << endl;
        } else {
            cout << "No" << endl;
            cout << 1 << " " << dist + 1 << endl;
        }
    }
}
 
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    cout.precision(12);
 
    bool FILEIO = 1;
    if (FILEIO and fopen("in.txt", "r")) {
        freopen("in.txt", "r", stdin);
    }
 
    int tc;
    cin >> tc;
    for (int tcase = 1; tcase <= tc; tcase++) {
        solve();
    }
 
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.