LOJ#6282. 数列分块入门 6

一个动态的插入过程,还需要带有查询操作。

我可以把区间先分块,然后每个块块用vector来维护它的插入和查询操作,但是如果我现在这个块里的vector太大了,我可能的操作会变的太大,所以这时候我需要把现在里面的数全部拿出来,然后进行重构,然后再进行后面的操作。

#include<map>
#include<set>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<string>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define lowbit(x) (x & (-x))

typedef unsigned long long int ull;
typedef long long int ll;
const double pi = 4.0*atan(1.0);
const int inf = 0x3f3f3f3f;
const int maxn = 200005;
const int maxm = 400;
const int mod = 10007;
using namespace std;

int n, m, tol, T;
int block;
int a[maxn];
int b[maxn];
int belong[maxn];
vector<int> v[maxn];

void init() {
    memset(a, 0, sizeof a);
    memset(b, 0, sizeof b);
    memset(belong, 0, sizeof belong);
}

int L(int x) {
    return (x-1) * block + 1;
}

int R(int x) {
    return min(n, x*block);
}

pair<int, int> query(int x) {
    int t = 1;
    while(x > v[t].size()) {
        x -= v[t].size();
        t++;
    }
    return make_pair(t, x-1);
}

void rebuild() {
    int num = 1;
    for(int i=1; i<=belong[n]; i++) {
        for(auto j : v[i])    b[num++] = j;
        v[i].clear();
    }
    int block2 = sqrt(num);
    for(int i=1; i<=num; i++)     belong[i] = (i-1) / block2 + 1;
    for(int i=1; i<=num; i++)    v[belong[i]].push_back(a[i]);
    block = block2;
    n = num;
}

void update(int l, int r) {
    pair<int, int > x = query(l);
    v[x.first].insert(v[x.first].begin()+x.second, r);
    if(v[x.first].size() > 20 * block)    rebuild();
}

int main() {
    while(~scanf("%d", &n)) {
        block = sqrt(n);
        for(int i=1; i<=n; i++) {
            scanf("%d", &a[i]);
            belong[i] = (i-1) / block + 1;
        }
        for(int i=1; i<=n; i++) {
            v[belong[i]].push_back(a[i]);
        }
        m = n;
        while(m--) {
            int op, l, r, c;
            scanf("%d%d%d%d", &op, &l, &r, &c);
            if(op == 0) {
                update(l, r);
            } else {
                pair<int, int> x = query(r);
                printf("%d
", v[x.first][x.second]);
            }
        }
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Jiaaaaaaaqi/p/9382330.html