LOJ 数列分块入门2

LOJ 数列分块入门2

题目:

题解:

  • 对每一个块排序,这样在查找个数时就能用二分找出块内<c * c的元素个数。
  • 暴力修改一段区间时,那一段区间所处的块要重新排序。因为局部混乱就已经导致了整个块不具有了单调性。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define N 500005
using namespace std;

struct Blo {int l, r, tag;} blo[N];
int n, size, num;
int a[N], b[N], bel[N];

int read() {
    int 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;
}

void reset(int x) {
    for (int i = blo[x].l; i <= blo[x].r; i++) b[i] = a[i];
    sort(b + blo[x].l, b + 1 + blo[x].r);
}

void update(int l, int r, int c) {
    if(bel[l] == bel[r]) {
        for (int i = l; i <= r; i++) a[i] += c;
        reset(bel[l]);
        return;
    }
    for (int i = l; i <= blo[bel[l]].r; i++) a[i] += c; reset(bel[l]);
    for (int i = r; i >= blo[bel[r]].l; i--) a[i] += c; reset(bel[r]);
    for (int i = bel[l] + 1; i < bel[r]; i++) blo[i].tag += c;
}

int ask(int l, int r, int c)
{
    int ans = 0;
    if(bel[l] == bel[r]) {
        for (int i = l; i <= r; i++)
            if (a[i] + blo[bel[l]].tag < c) ans++;
        return ans;
    }
    for (int i = l; i <= blo[bel[l]].r; i++)
        if (a[i] + blo[bel[i]].tag < c) ans++;
    for (int i = r; i >= blo[bel[r]].l; i--)
        if (a[i] + blo[bel[i]].tag < c) ans++;
    for (int i = bel[l] + 1; i < bel[r]; i++)
        ans += lower_bound(b + blo[i].l, b + 1 + blo[i].r, c - blo[i].tag) - b - blo[i].l;
    return ans;
}

void build() {
    size = (int)sqrt(n), num = n / size;
    if(n % size) num++;
    for (int i = 1; i <= num; i++) {
        blo[i].l = (i - 1) * size + 1;
        blo[i].r = i * size;
    }
    blo[num].r = n;
    for (int i = 1; i <= n; i++) bel[i] = (i - 1) / size + 1;
    for (int i = 1; i <= num; i++) sort(b + blo[i].l, b + 1 + blo[i].r);
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        a[i] = read();
        b[i] = a[i];
    }
    build();
    for (int i = 1; i <= n; i++) {
        int op = read(), l = read(), r = read(), c = read();
        if(!op) update(l, r, c);
        else printf("%d\n", ask(l, r, c * c));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/BigYellowDog/p/11241614.html