ZYK_luogu @ 2023-04-22 13:19:28
今天学线段树,顺便借鉴了一下题解(我还急着赶五一休假的作业啊!!!),样例都能过,结果就错了。
#include <iostream>
using namespace std;
#define maxn 100005
struct tree{
int l, r;
long long key;
bool add;
} t[4 * maxn];
int n, m;
int a[maxn];
void build(int p, int l, int r) {
t[p].l = l, t[p].r = r;
if(l == r) {
t[p].key = a[l];
return;
}
int mid = l + r >> 1;
build(p * 2, l, mid);
build(p * 2 + 1, mid + 1, r);
t[p].key = t[p * 2].key + t[p * 2 + 1].key;
}
void update(int p) {
if(t[p].add) {
t[p * 2].key += t[p].add * (t[p * 2].r - t[p * 2].l + 1);
t[p * 2 + 1].key += t[p].add * (t[p * 2 + 1].r - t[p * 2 + 1].l + 1);
t[p * 2].add += t[p].add;
t[p * 2 + 1].add += t[p].add;
t[p].add = 0;
}
}
void change(int p, int x, int y, int z) {
if(x <= t[p].l && y >= t[p].r) {
t[p].key += z * (t[p].r - t[p].l + 1);
t[p].add += z;
return;
}
update(p);
int mid = t[p].l + t[p].r >> 1;
if(x <= mid) change(p * 2, x, y, z);
if(y > mid) change(p * 2 + 1, x, y, z);
t[p].key = t[p * 2].key + t[p * 2 + 1].key;
}
long long ask(int p, int x, int y) {
if(x <= t[p].l && y >= t[p].r)
return t[p].key;
update(p);
int mid = t[p].l + t[p].r >> 1;
long long ans = 0;
if(x <= mid) ans += ask(p * 2, x, y);
if(y > mid) ans += ask(p * 2 + 1, x, y);
return ans;
}
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i ++)
cin >> a[i];
build(1, 1, n);
while(m --) {
int q, x, y, z;
cin >> q;
if(q == 1) {
cin >> x >> y >> z;
change(1, x, y, z);
} else {
cin >> x >> y;
cout << ask(1, x, y) << endl;
}
}
return 0;
}
by __yabnto__ @ 2023-04-22 13:32:00
照着题解抄,emmm……
by Vector_Math @ 2023-04-22 13:33:00
借鉴题解也会被棕名哦!
by Vector_Math @ 2023-04-22 13:33:35
第2
by Wisdom114514 @ 2023-04-22 13:36:26
《照着题解抄》
by __yabnto__ @ 2023-04-22 13:37:55
已举报
by FstAutoMaton @ 2023-04-22 13:38:12
6
by S0CRiA @ 2023-04-22 13:38:12
楼上几位刚学线段树不看题解的吗。。。
by S0CRiA @ 2023-04-22 13:38:29
注意 add
的类型
by xujunlang2011 @ 2023-04-22 13:39:08
emm……
by __yabnto__ @ 2023-04-22 13:39:22
我没学线段树