LOJ6283 数列分块入门7

LOJ6283 数列分块入门 7

标签

  • 分块入门

前言

简明题意

  • 维护序列,需要支持三种操作:
    1. 区间加
    2. 区间乘
    3. 单点查

思路

  • 学过线段树的同学应该在洛谷上做过这一题,难点在于有多种标记该怎么处理。我在线段树分类下的一篇文章中讲过如何处理多种标记。
  • 这里分块和线段树是一样的,设一个tag_plus[]和tag_mult[]两种标记。该如何更新标记?实际上我们第一步应该定义标记运算的法则,也就是,如果同时存在两种标记,应该先计算哪一个呢?定义好了法则,然后就很容易可以更新标记了。

注意事项

  • 还是要注意最后一块是不完整的。特别是重构块时,特判一下最后一块。

总结

  • 重构块操作可以单独写出来~

AC代码

#pragma GCC optimize(2)
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;

const int maxn = 1e5 + 10;
const int mod = 10007;

int read()
{
    int x = 0, f = 1; char ch = getchar();
    while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
    while (ch >= '0'&&ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
    return x * f;
}

int n, a[maxn];
int pos[maxn], len, tag_plus[maxn], tag_mult[maxn];

void reset(int id)
{
    for (int i = id * len - len + 1; i <= min(id * len, n); i++)
        a[i] = (a[i] * tag_mult[id] + tag_plus[id]) % mod;
    tag_mult[id] = 1, tag_plus[id] = 0;
}

void change_plus(int l, int r, int c) 
{
    reset(pos[l]);
    if (pos[l] != pos[r]) reset(pos[r]);

    for (int i = l; i <= min(pos[l] * len, r); i++)
        a[i] = (a[i] + c) % mod;
    if (pos[l] != pos[r])
        for (int i = pos[r] * len - len + 1; i <= r; i++)
            a[i] = (a[i] + c) % mod;
    for (int i = pos[l] + 1; i <= pos[r] - 1; i++) tag_plus[i] = (tag_plus[i] + c) % mod;
}

void change_mult(int l, int r, int c) 
{
    reset(pos[l]);
    if (pos[l] != pos[r]) reset(pos[r]);

    for (int i = l; i <= min(pos[l] * len, r); i++) 
        a[i] = a[i] * c % mod;
        
    if (pos[l] != pos[r])
        for (int i = pos[r] * len - len + 1; i <= r; i++) 
            a[i] = a[i] * c % mod;

    for (int i = pos[l] + 1; i <= pos[r] - 1; i++) {
        tag_plus[i] *= c;
        tag_mult[i] *= c;
        tag_plus[i] %= mod, tag_mult[i] %= mod;
    }
}

int ask(int l, int r, int c) {
    return (a[r] * tag_mult[pos[r]] + tag_plus[pos[r]]) % mod;
}

void solve() {
    fill(tag_mult + 1, tag_mult + 1 + maxn - 10, 1);
    scanf("%d", &n);
    len = sqrt(n);
    for (int i = 1; i <= n; i++)
    a[i] = read(), pos[i] = (i - 1) / len + 1;

    for (int i = 1; i <= n; i++) {
        int opt, l, r, c;
        opt = read(), l = read(), r = read(), c = read();
        if (opt == 0)
            change_plus(l, r, c);
        else if (opt == 1)
            change_mult(l, r, c);
        else
            printf("%d\n", (a[r] * tag_mult[pos[r]] + tag_plus[pos[r]]) % mod);
    }
}

int main() {
    freopen("Testin.txt", "r", stdin);
    freopen("Testout.txt", "w", stdout);
    solve();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/danzh/p/11364087.html
0条评论
添加一条新回复