P13825 【模板】线段树 1.5 离散化题解
既然标签中有离散化,那么就来一发离散化题解。
前置知识:离散化思想,普通懒标记线段树。
做法
如果
注意到上述做法的瓶颈在于
如果你接触过离散化,很容易往离散化方面思考。这一思想让我们发现一个重要的事实:很多位置的变化量是一致的!
具体地,令所有操作的
所以我们可以直接让每个
对于初始值,直接使用等差数列求和公式即可。
对于修改和查询,在每个线段树节点上记录其所对应的原序列上的区间,即可按照正常方法操作。
于是我们得到了一个预处理时间复杂度
和动态开点线段树的对比
本做法存在如下优势:
- 可以直接处理初始值,无需单独计算;
- 空间复杂度是线性的
O(m) ,优于动态开点线段树的O(m\log n) 。
但也存在要求离线的劣势。
代码
注意单次查询的答案的最大值是
需要用 unsigned long long 存储。
::::warning[完整代码,诚信学习,请勿抄袭。]
#include <bits/stdc++.h>
using namespace std;
#define LML return
#define NL 0
const int N = int(1e5) + 10;
int l[N], r[N], op[N], val[N], a[N << 1], sl[N << 2], sr[N << 2];
struct node {
int pl, pr;
unsigned long long lz, sum;
} tr[N << 4];
void Givetag(int p, unsigned long long k) {
tr[p].lz += k;
tr[p].sum += k * (tr[p].pr - tr[p].pl + 1);
}
void Pushdown(int p) {
if (tr[p].lz) {
Givetag(p << 1, tr[p].lz);
Givetag(p << 1 | 1, tr[p].lz);
tr[p].lz = 0;
}
}
void Build(int p, int x, int y) {
tr[p].pl = sl[x];
tr[p].pr = sr[y];
tr[p].lz = 0;
tr[p].sum = ((1ull * (sl[x] + sr[y]) * (sr[y] - sl[x] + 1)) >> 1);
if (x == y) return;
int mid = x + y >> 1;
Build(p << 1, x, mid);
Build(p << 1 | 1, mid + 1, y);
}
void Modi(int p, int x, int y, unsigned long long k) {
if (x <= tr[p].pl && tr[p].pr <= y) return Givetag(p, k);
Pushdown(p);
if (x <= tr[p << 1].pr) Modi(p << 1, x, y, k);
if (y >= tr[p << 1 | 1].pl) Modi(p << 1 | 1, x, y, k);
tr[p].sum = tr[p << 1].sum + tr[p << 1 | 1].sum;
}
unsigned long long Query(int p, int x, int y) {
if (x <= tr[p].pl && tr[p].pr <= y) return tr[p].sum;
Pushdown(p);
if (y <= tr[p << 1].pr) return Query(p << 1, x, y);
if (x >= tr[p << 1 | 1].pl) return Query(p << 1 | 1, x, y);
return Query(p << 1, x, y) + Query(p << 1 | 1, x, y);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> op[i] >> l[i] >> r[i];
a[i] = l[i];
a[i + m] = r[i];
if (op[i] == 1) cin >> val[i];
}
sort(a + 1, a + (m << 1 | 1));
int k = unique(a + 1, a + (m << 1 | 1)) - a - 1, cnt = 0;
if (a[1] > 1) {
sl[1] = 1;
sr[1] = a[1] - 1;
cnt = 1;
}
a[k + 1] = n;
for (int i = 1; i <= k; i++) {
cnt++;
sl[cnt] = sr[cnt] = a[i];
if (a[i] + 1 < a[i + 1]) {
cnt++;
sl[cnt] = a[i] + 1;
sr[cnt] = a[i + 1] - 1;
}
}
Build(1, 1, cnt);
for (int i = 1; i <= m; i++) {
if (op[i] == 1) Modi(1, l[i], r[i], val[i]);
else cout << Query(1, l[i], r[i]) << '\n';
}
LML NL;
}
::::