很lj的线段树
查看原帖
很lj的线段树
537520
DESTRUCTION_3_2_1楼主2022/8/27 17:08
#include <bits/stdc++.h>
#define int long long
#define ls (x << 1)
#define rs (x << 1 | 1)
using namespace std;
const int MAXN = 1e5 + 5;
int n, m, x, y, k, opt, a[MAXN];
struct node{
	int L;
	int R;
	int value;
	int tag;
}tr[4 * MAXN];
inline int read(){
	int X=0,w=0;
	char ch=0;
	while(!isdigit(ch))
	{
		w|=ch=='-';
		ch=getchar();
	}
	while(isdigit(ch))
	{
		X=(X<<3)+(X<<1)+(ch^48);
		ch=getchar();
	}
	return w?-X:X;
}
void build (int x, int L, int R)
{
	tr[x].L = L; tr[x].R = R;
	if (L == R)
	{
		tr[x].value = a[L];
		return;
	}
	int mid = (L + R) >> 1;
	build (ls, L, mid);
	build (rs, mid + 1, R);
	tr[x].value = tr[ls].value + tr[rs].value;
}
inline void lazy_tag (int x)
{
	if (tr[x].tag != 0)
	{
		tr[ls].tag += tr[x].tag;
		tr[rs].tag += tr[x].tag;
		tr[ls].value += (tr[ls].R - tr[ls].L + 1) * tr[x].tag;
		tr[rs].value += (tr[rs].R - tr[rs].L + 1) * tr[x].tag;
		tr[x].tag = 0;
	}
}
inline void change (int x, int L, int R, int v)// v 为 修改的值
{
	if (tr[x].L >= L and R >= tr[x].R)
	{
		tr[x].tag += v;
		tr[x].value += (tr[x].R - tr[x].L + 1) * v;
		return;
	}
	lazy_tag (x);
	int mid = (tr[x].L + tr[x].R) >> 1;
	if (tr[ls].R >= L)
		change (ls, L, mid, v);
	if (tr[rs].L <= R)
		change (rs, mid + 1, R, v);
	tr[x].value = tr[ls].value + tr[rs].value;
}
inline int ask (int x, int L, int R)
{
	if (tr[x].L >= L and tr[x].R <= R)
		return tr[x].value;
	if (tr[x].R < L or tr[x].L > R)
		return 0;
	lazy_tag (x);
	int ans = 0;
	if (tr[ls].R >= L)
		ans += ask (ls, L, R);
	if (tr[rs].L <= R)
		ans += ask (rs, L, R);
	return ans;
}
signed main(void)
{
	//freopen("input.in","r",stdin);
	//freopen("output.out","w",stdout);
	n = read(); m = read();
	for (int i=1; i<=n; i++)
		a[i] = read();
	build (1, 1, n);
	while (m--)
	{
		opt = read();
		if (opt == 1)
		{
			x = read(); y = read(); k = read();
			change (1, x, y, k);
		}
		if (opt == 2)
		{
			x = read(); y = read();
			cout << ask (1, x, y) << endl;
		}
	}
	//fclose(stdin);
	//fclose(stdout);
	return 0;
}

样例能过。。。。

2022/8/27 17:08
加载中...