【函数式Trie】51NOD 1295 XOR key

通道

思路:每个数建个31位的树,处理好关系即可

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 60007;
const int BIT = 32;

int n, m;
int tot, s[N * BIT], a[N * BIT][2], root[N];

void Insert(int x, int &y, int num, int d) {
    s[y = ++tot] = s[x] + 1;
    if (d < 0) return ;
    int dig = num >> d & 1;
    a[y][dig ^ 1] = a[x][dig ^ 1];
    Insert(a[x][dig], a[y][dig], num, d - 1);
}
int Query(int x, int y, int num, int d) {
    if (d < 0) return 0;
    int dig = num >> d & 1;
    if (s[a[y][dig ^ 1]] - s[a[x][dig ^ 1]]) 
        return (1<<d) + Query(a[x][dig ^ 1], a[y][dig ^ 1], num, d - 1);
    return Query(a[x][dig], a[y][dig], num, d - 1);
}

template <class T>
inline bool rd(T &ret) {
    char c; int sgn;
    if(c = getchar() , c == EOF) return false;
    while(c != '-' && (c < '0' || c > '9')) c = getchar();
    sgn = (c == '-') ? -1 : 1;
    ret = (c == '-') ? 0 : (c - '0');
    while(c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c - '0');
    ret *= sgn;
    return true;
}
template <class T>
inline void pt(T x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if(x > 9) pt(x / 10);
    putchar(x % 10 + '0');
}

int main() {
    rd(n), rd(m);
    Insert(root[0], root[1], 0, 31);
    for (int i = 1; i <= n; ++i) {
        int v; rd(v);
        Insert(root[i], root[i + 1], v, 31);
    }
    while (m--) {
        int v, l, r; rd(v), rd(l), rd(r); ++l, ++r;
        pt(Query(root[l], root[r + 1], v, 31)), putchar('\n');
    }
    return 0;
}
View Code

 

posted @ 2015-10-24 15:45  mithrilhan  阅读(266)  评论(0编辑  收藏  举报