HDU6191持久化字典树+DFS序

#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e5 + 7;

int val[maxn];
vector<int>g[maxn];
int in[maxn], out[maxn];
int rt[maxn], tot, time_tag;
struct node
{
    int lc, rc, v; //lc = 0, rc = 1;
}t[maxn * 35];
int update(int last, int x, int d)
{
    int now = ++ tot;
    t[now] = t[last];
    t[now].v ++;
    if(d < 0) return now;
    int bit = x >> d & 1;
    if(bit) {
        t[now].rc = update(t[last].rc, x, d-1);
    } else {
        t[now].lc = update(t[last].lc, x, d-1);
    }
    return now;
}
int query(int st, int ed, int x, int d)
{
    if(d < 0) return 0;
    int bit = x >> d & 1;
    if(bit) {
        int cnt = t[ t[ed].lc ].v - t[ t[st].lc ].v;
        if(cnt > 0) return (1<<d) + query(t[st].lc, t[ed].lc, x, d - 1);
        else return query(t[st].rc, t[ed].rc, x, d - 1);
    } else {
        int cnt = t[ t[ed].rc ].v - t[ t[st].rc ].v;
        if(cnt > 0) return (1<<d) + query(t[st].rc, t[ed].rc, x, d - 1);
        else return query(t[st].lc, t[ed].lc, x, d - 1);
    }
}
void dfs(int u, int par)
{
    in[u] = ++time_tag;
    rt[time_tag] = update(rt[time_tag-1], val[u], 29);
    for(auto it : g[u]) {
        if(it != par) dfs(it, u);
    }
    out[u] = time_tag;
}
int main()
{
    int n, q;
    while(~scanf("%d %d", &n, &q)) {
        for(int i = 1;i <= n;i ++) g[i].clear();
        time_tag = tot = t[0].lc = t[0].rc = t[0].v = 0;
        rt[0] = update(rt[0], 0, 29);
        for(int i = 1;i <= n;i ++) scanf("%d", &val[i]);
        for(int i = 2;i <= n;i ++) {
            int fa;
            scanf("%d", &fa);
            g[fa].push_back(i);
            g[i].push_back(fa);
        }
        dfs(1, -1);
        while(q --) {
            int u, x;
            scanf("%d %d", &u, &x);
            printf("%d\n", query(rt[in[u]-1], rt[out[u]], x, 29) );
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36876305/article/details/80466558
今日推荐