BZOJ 2741【FOTILE模擬賽】L 分塊+可持久化Trie樹

題目大意

給出一個序列,求[l, r]中的最大連續xor  和。
強制在線

思路

先把整個序列分成n     塊,預處理每一塊的開頭到每個數字的最大連續xor  和。這個我們只需處理出前綴xor  和,之後用可持久化Trie樹就可以搞定。這樣詢問的右邊就是整塊的了。剩下左邊的隨便暴力一下就能過了。。

CODE

#define _CRT_SECURE_NO_WARNINGS

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 15000
using namespace std;

int cnt, asks;
int src[MAX];
int blocks, size;

int belong[MAX];
int st[MAX], ed[MAX];

struct Trie{
    Trie *son[2];
    int cnt;
}mempool[MAX * 100], *C = mempool;
Trie *trie[MAX], **tree = trie + 1;

Trie *NewTrie(Trie *_, Trie *__, int ___)
{
    C->son[0] = _;
    C->son[1] = __;
    C->cnt = ___;
    return C++;
}

Trie *Insert(Trie *consult, int c, int deep)
{
    if(!deep)
        return NewTrie(NULL, NULL, consult->cnt + 1);
    if(!(~c&deep))
        return NewTrie(consult->son[0], Insert(consult->son[1], c, deep >> 1), consult->cnt + 1);
    else
        return NewTrie(Insert(consult->son[0], c, deep >> 1), consult->son[1], consult->cnt + 1);
}

int GetMax(Trie *l, Trie *r, int x, int deep)
{
    if(!deep)
        return 0;
    bool dir = x&deep ? 0:1;
    if(r->son[dir]->cnt - l->son[dir]->cnt)
        return deep + GetMax(l->son[dir], r->son[dir], x,deep >> 1);
    else
        return GetMax(l->son[!dir], r->son[!dir], x, deep >> 1);
}

int ans[120][MAX];

int main()
{
    cin >> cnt >> asks;
    for(int i = 1; i <= cnt; ++i) {
        scanf("%d", &src[i]);
        src[i] ^= src[i - 1];
    }
    size = sqrt(cnt + 1);
    memset(st, -1, sizeof(st));
    for(int i = 0; i <= cnt; ++i) {
        belong[i] = i / size;
        if(st[belong[i]] == -1)
            st[belong[i]] = i;
        ed[belong[i]] = i;
    }
    blocks = belong[cnt];

    tree[-1] = NewTrie(C, C, 0);
    tree[0] = Insert(tree[-1], 0, 1 << 30);
    for(int i = 1; i <= cnt; ++i)
        tree[i] = Insert(tree[i - 1], src[i], 1 << 30);

    for(int i = 0; i <= blocks; ++i)
        for(int j = st[i]; j <= cnt; ++j)
            ans[i][j] = max(GetMax(tree[st[i] - 1], tree[j], src[j], 1 << 30), j ? ans[i][j - 1] : 0);
    int last_ans = 0;
    for(int x, y, i = 1; i <= asks; ++i) {
        scanf("%d%d", &x, &y);
        x = ((long long)x + last_ans) % cnt + 1;
        y = ((long long)y + last_ans) % cnt + 1;
        if(x > y)   swap(x, y);
        --x;
        int t = belong[x] + 1;
        last_ans = ans[t][y];
        for(int j = min(st[t] - 1, y); j >= x; --j)
            last_ans = max(last_ans, GetMax(tree[x - 1], tree[y], src[j], 1 << 30));
        printf("%d\n", last_ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章