https://ac.nowcoder.com/acm/contest/24154/E
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n, m;
LL w[N];
struct Node
{
int l, r;
LL sum, add;
}tr[N * 4];
void pushup(int u)
{
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void pushdown(int u)
{
auto &root = tr[u], &left = tr[u << 1], &right = tr[u << 1 | 1];
if (root.add)
{
left.add += root.add, left.sum += (LL)(left.r - left.l + 1) * root.add;
right.add += root.add, right.sum += (LL)(right.r - right.l + 1) * root.add;
root.add = 0;
}
}
void build(int u, int l, int r)
{
if (l == r) tr[u] = {l, r, w[r], 0};
else
{
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
void modify(int u, int l, int r, int d)
{
if (tr[u].l >= l && tr[u].r <= r)
{
tr[u].sum += (LL)((tr[u].r - tr[u].l + 1) * d);
tr[u].add += d;
}
else // 一定要分裂
{
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) modify(u << 1, l, r, d);
if (r > mid) modify(u << 1 | 1, l, r, d);
pushup(u);
}
}
LL query(int u, int l, int r)
{
if (tr[u].l >= l && tr[u].r <= r) return tr[u].sum;
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
LL sum = 0;
if (l <= mid) sum = query(u << 1, l, r);
if (r > mid) sum += query(u << 1 | 1, l, r);
return sum;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ ) scanf("%d", &w[i]);
build(1, 1, n);
int op;
int l, r, d;
while (m -- )
{
cin >> op >> l >> r;
if (op == 1)
{
cin >> d;
modify(1, l, r, -d);
}
else printf("%lld\n", query(1, l, r));
}
return 0;
}
1.题目后台数据不严谨,理论上血量可以为最大值,所以LL定义,但是成功ac的代码里可以不用LL
2.在做这道题时按照yxc的 一个简单的整数问题2 https://www.acwing.com/problem/content/244/
来写,在modify强制转换tr[u].sum += (LL)(tr[u].r - tr[u].l + 1) *d;这一步中,反而过不去最后一个案例,就在于强制转换出了问题 ,所以出现int long long 运算,之后我会优先把全部先定义成long long
相似题型 https://www.acwing.com/problem/content/1266/