CodeChef Chef and Churu(分块)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hnust_Derker/article/details/80341335

题目链接

题意:
      n个数m个操作,操作分两种:
1  x  yaxy
2  x  yi=xyfi,其中fi=j=liriaj

思路:
    可以考虑对f分块,维护每个块内的和,统计每个下标i在每个块中出现的次数,那么对于1操作,假设在块bx出现了t次,x位置当前值为ax,那么bx的更新为:sumb=sumb+tytax,对于块内的和,直接树状数组更新求值,时间复杂度O(nnlogn)

#include<bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
const int maxn = 1e5 + 10;
using namespace std;

int n, m, T, kase = 1, block_size;
int a[maxn], l[maxn], r[maxn];
ll block_sum[maxn], C[maxn];
int show[350][maxn];

void update(int x, int val) { for(; x <= n; x += x & -x) C[x] += val; }
ll get_sum(int x) { ll ans = 0; for(; x; x -= x & -x) ans += C[x]; return ans; }

void init() {
    int st = 0, num = 0;
    block_size = sqrt(n) + 2;
    memset(block_sum, 0, sizeof block_sum);
    memset(C, 0, sizeof C);
    for(int i = 0; i < n; i++) {
        update(l[i] + 1, 1);
        update(r[i] + 2, -1);
        st++;
        if(st == block_size || i == n - 1) {
            for(int i = 0; i < n; i++) {
                show[num][i] = get_sum(i + 1);
                block_sum[num] += (ll)show[num][i] * a[i];
            }
            memset(C, 0, sizeof C);
            num++; st = 0;
        }
    }
    for(int i = 1; i <= n; i++) update(i, a[i - 1]);
}

ull query(int x, int y) {
    int b1 = (x + 1) / block_size;
    int b2 = (y + 1) / block_size;
    ull ans = 0;
    if(b1 == b2) {
        for(int i = x; i <= y; i++)
            ans += get_sum(r[i] + 1) - get_sum(l[i]);
        return ans;
    }
    for(int i = b1 + 1; i < b2; i++) ans += block_sum[i];
    int l1 = (b1 + 1) * block_size;
    int l2 = b2 * block_size;
    for(int i = x; i < l1; i++) ans += get_sum(r[i] + 1) - get_sum(l[i]);
    for(int i = l2; i <= y; i++) ans += get_sum(r[i] + 1) - get_sum(l[i]);
    return ans;
}

void update(int id, int x, int y) {
    a[id] = y;
    update(id + 1, -x);
    update(id + 1, y);
    int tot = n / block_size;
    if(n % block_size) tot++;
    for(int i = 0; i < tot; i++) {
        int tm = show[i][id];
        block_sum[i] += (ll)y * tm;
        block_sum[i] -= (ll)x * tm;
    }
}

int main() {
    while(scanf("%d", &n) != EOF) {
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);
        for(int i = 0; i < n; i++) {
            scanf("%d %d", &l[i], &r[i]);
            l[i]--; r[i]--;
        }
        init(); scanf("%d", &m);
        while(m--) {
            int op, x, y;
            scanf("%d %d %d", &op, &x, &y);
            if(op == 1) update(x - 1, a[x - 1], y);
            else printf("%llu\n", query(x - 1, y - 1));
        }
    }
    return 0;
}
阅读更多

没有更多推荐了,返回首页