LibreOJ #6280

题目链接:#6280. 数列分块入门 4

题目大意

给出一个长为 \(n\) 的数列,以及 \(n\) 个操作,操作涉及区间加法,区间求和。

solution

我们可以进行分块, 然后对于操作有:

修改操作: 对于整块我们直接加和并记录一下, 对于散块,我们直接暴力加和

查询操作: 对于整块,我们直接加和即可, 对于散块我们讲元素在加上我们记录的值即可

Code:

/**
*    Author: Alieme
*    Data: 2020.9.8
*    Problem: LibreOJ #6280
*    Time: O()
*/
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>

#define int long long
#define rr register

#define inf 1e9
#define MAXN 100010

using namespace std;

inline int read() {
	int s = 0, f = 0;
	char ch = getchar();
	while (!isdigit(ch)) f |= ch == '-', ch = getchar();
	while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
	return f ? -s : s;
}

void print(int x) {
	if (x < 0) putchar('-'), x = -x;
	if (x > 9) print(x / 10);
	putchar(x % 10 + 48);
}

int n, len;

int a[MAXN], v[MAXN], id[MAXN], sum[MAXN];

inline void add(int l, int r, int x) {
	int start = id[l], end = id[r];
	if (start == end) {
		for (rr int i = l; i <= r; i++) a[i] += x, sum[start] += x;
		return ;
	}
	for (rr int i = l; id[i] == start; i++) a[i] += x, sum[start] += x;
	for (rr int i = start + 1; i < end; i++) v[i] += x, sum[i] += x * len;
	for (rr int i = r; id[i] == end; i--) a[i] += x, sum[end] += x;
}

inline int query(int l, int r, int mod) {
	int start = id[l], end = id[r], ans = 0;
	if (start == end) {
		for (rr int i = l; i <= r; i++) ans = (ans + a[i] + v[start]) % mod;
		return ans;
	}
	for (rr int i = l; id[i] == start; i++) ans = (ans + a[i] + v[start]) % mod;
	for (rr int i = start + 1; i < end; i++) ans = (ans + sum[i]) % mod;
	for (rr int i = r; id[i] == end; i--) ans = (ans + a[i] + v[end]) % mod;
	return ans;
}

signed main() {
	n = read();
	len = sqrt(n);
	for (rr int i = 1; i <= n; i++) a[i] = read(), id[i] = (i - 1) / len + 1, sum[id[i]] += a[i];
	while (n--) {
		int opt = read(), l = read(), r = read(), c = read();
		if (opt == 0) add(l, r, c);
		if (opt == 1) cout << query(l, r, c + 1) << "\n";
	}
}
posted @ 2020-09-09 21:00  Aliemo  阅读(101)  评论(0编辑  收藏  举报