Saturday, January 27, 2024

[Hackerearth] Xorzilla

 

Problem Link    : Xorzilla
Category        : Graph Theory, Bit
Contest         : January Easy '24

#include "bits/stdc++.h"
using namespace std;
#define int     long long int
#define endl    '\n'
 
const int maxn = 2e5 + 5;
const int logn = 20;
 
int n;
vector<int> arr;
vector<vector<int>> graph;
vector<int> depth;
vector<vector<int>> father;
vector<int> cumxor;
 
void dfs(int u, int p, int lvl) {
    depth[u] = lvl;
    cumxor[u] = arr[u] ^ cumxor[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;
        }
        father[v][0] = u;
        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];
}
 
int getMax(int u, int v, int x) {
    int lca = findLca(u, v);
    int xorsum = cumxor[u] ^ cumxor[v] ^ arr[lca];
    int dist = depth[u] + depth[v] - 2 * depth[lca];
    if (dist % 2) {
        return xorsum;
    }
    int maxi = 0;
    for (int i = 30; i >= 0; i--) {
        bool bit = xorsum >> i & 1LL;
        if (bit == 0) {
            if (maxi + (1LL << i) <= x) {
                maxi = maxi + (1LL << i);
            }
        }
    }
    return xorsum ^ maxi;
}
 
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++) {
        cin >> n;
        arr.clear(); arr.resize(n + 1);
        depth.clear(); depth.resize(n + 1);
        graph.clear(); graph.resize(n + 1);
        cumxor.clear(); cumxor.resize(n + 1);
        father = vector<vector<int>>(n + 1, vector<int>(logn));
        for (int e = 1; e < n; e++) {
            int u, v;
            cin >> u >> v;
            graph[u].push_back(v);
            graph[v].push_back(u);
        }
        for (int i = 1; i <= n; i++) {
            cin >> arr[i];
        }
        dfs(1, 0, 1);
        int q;
        cin >> q;
        while (q--) {
            int x, u, v;
            cin >> x >> u >> v;
            cout << getMax(u, v, x) << endl;
        }
    }
}

No comments:

Post a Comment

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