比赛 2025.3.29 评测结果 AAAAAAAAAA
题目名称 幸运数字 最终得分 100
用户昵称 flyfree 运行时间 13.204 s
代码语言 C++ 内存使用 168.63 MiB
提交时间 2025-03-29 11:54:35
显示代码纯文本
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pir pair<ll,ll>
#define ls first
#define rs second
#define mp make_pair
#define mod
#define MAXN 20010
#define qmod(x) (x>mod?x-mod:x)
inline ll read(){
    ll x = 0,f = 1;
    char c = getchar();
    while(c < '0'||c > '9'){
        if(c == '-')f = -1;
        c = getchar();
    }
    while(c >= '0'&&c <= '9'){
        x = x*10+c-'0';
        c = getchar();
    }
    return x*f;
}
struct node_matrix{
    ll p[70];
    void insert(ll val){
        for(int i = 60;i >= 0; --i){
            if(val & (1ll << i)){
                if(!p[i]){
                    p[i] = val;
                    return;
                }else val ^= p[i];
            }
        }
    }
    void merge(node_matrix S){
        for(int i = 60;i >= 0; --i){
            if(S.p[i])insert(S.p[i]);
        }
    }
    ll query(){
        ll res = 0;
        for(int i = 60;i >= 0; --i){
            if(p[i] && (res & (1ll << i)) == 0){
                res ^= p[i];
            }
        }
        return res;
    }
}dis[MAXN][21];


ll hd[MAXN],ed[MAXN * 2],nxt[MAXN * 2];
ll idx,n,q;
void build(ll x, ll y){
    ++ idx;
    nxt[idx] = hd[x];
    ed[idx] = y;
    hd[x] = idx;
}
ll fa[MAXN][21],dep[MAXN],g[MAXN];

void dfs(ll now, ll p){
    dep[now] = dep[p] + 1;
    fa[now][0] = p;
    dis[now][0].insert(g[now]);
    for(int i = 1;i <= 20; ++i)fa[now][i] = fa[fa[now][i - 1]][i - 1];
    for(int i = 1;i <= 20; ++i){
        dis[now][i].merge(dis[now][i - 1]);
        dis[now][i].merge(dis[fa[now][i - 1]][i - 1]);
    }
    for(int i = hd[now];i;i = nxt[i]){
        ll y = ed[i];
        if(y == p)continue;
        dfs(y, now);
    }
}


ll lca(ll x, ll y){
    node_matrix res = {0};
    if(dep[x] < dep[y])swap(x, y);
    for(int i = 20;i >= 0; --i){
        if(dep[fa[x][i]] >= dep[y]){
            res.merge(dis[x][i]);
            x = fa[x][i];
        }
    }
    if(x == y){
        res.insert(g[x]);
        return res.query();
    }
    for(int i = 20;i >= 0; --i){
        if(fa[x][i] != fa[y][i]){
            res.merge(dis[x][i]);
            res.merge(dis[y][i]);
            x = fa[x][i];
            y = fa[y][i];
        }
    }
    res.insert(g[x]);
    res.insert(g[y]);
    res.insert(g[fa[x][0]]);
    return res.query();  
}


int main(){
    freopen("luckynum.in", "r", stdin);
    freopen("luckynum.out", "w", stdout);
    n = read(),q = read();
    for(int i = 1;i <= n; ++i)g[i] = read();
    for(int i = 1;i < n; ++i){
        ll x = read(),y = read();
        build(x, y);
        build(y, x);
    }
    dfs(1, 0);
    for(int i = 1;i <= q; ++i){
        ll x = read(),y = read();
        cout << lca(x, y) << endl;
    }
    return 0;
}