Skip to content

树状数组(区修区查) ​

题面

c++
#include <iostream>
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include<iomanip>
#include <string.h>
#include<limits.h>
#define ll long long 
using namespace std;
ll n, m, s1[100005], s2[100005], op, x, y, k;
int lowbit(ll x)//提取低位幂
{
	return x & -x;
}
void change(ll s[], ll x, ll k)//向后修
{
	while (x <= n)
	{
		s[x] += k;
		x += lowbit(x);
	}
}
ll query(ll s[], ll x)//向前查
{
	ll t = 0;
	while (x)
	{
		t += s[x];
		x -= lowbit(x);
	}
	return t;
}
int main()
{
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		cin >> k;
		change(s1, i, k); change(s1, i + 1, -k);//差分
		change(s2, i, k * (i - 1)); change(s2, i + 1, -k * i);
	}
	while (m--)
	{
		cin >> op >> x >> y;
		if (op == 1)//区修
		{
			cin >> k;
			change(s1, x, k); change(s1, y + 1, -k);//差分
			change(s2, x, k * (x - 1)); change(s2, y + 1, -k * y);
		}
		else//区查
		{
			k = (query(s1, y) * y - query(s2, y)) - (query(s1, x - 1) * (x - 1) - query(s2, x - 1));
			cout << k << endl;
		}
	}
	return 0;
}