跳到正文

剪贴板

剪贴板 cqzhpdmb

原文
剪贴板信息

剪贴板信息

收录
更新
C++
//线段树模版
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e6 + 10;

struct Tag {
	int add;
	
	Tag(const int& _add = 0) : add(_add) {}
	
	inline bool empty() const {
		return add == 0;
	}
	
	inline Tag& operator+= (const Tag& other) {
		add += other.add;
		return *this;
	}
};

struct Info {
	int l, r;
	int sum;
	
	Info(const int& _l = 0, const int& _r = 0,
		 const int& _sum = 0) : l(_l), r(_r), sum(_sum) {}
	
	inline Info& operator+= (const Tag& t) {
		sum += (r - l + 1) * t.add;
		return *this;
	}
};
	
inline Info operator+ (const Info& lhs, const Info& rhs) {
	return Info(lhs.l, rhs.r, lhs.sum + rhs.sum);
}

int n, m;
int a[N];
Info segt[N << 2];
Tag tag[N << 2];

inline void pushup(int cur) {
	segt[cur] = segt[cur * 2] + segt[cur * 2 + 1];
}

inline void pushdown(int cur) {
	if (tag[cur].empty())
		return;
	segt[cur * 2] += tag[cur], tag[cur * 2] += tag[cur];
	segt[cur * 2 + 1] += tag[cur], tag[cur * 2 + 1] += tag[cur];
	tag[cur] = Tag();
}

void build(int cur, int l, int r) {
	tag[cur] = Tag();
	if (l == r) {
		segt[cur] = Info(l, r, a[l]);
		return;
	}
	const int mid = (l + r) / 2;
	build(cur * 2, l, mid);
	build(cur * 2 + 1, mid + 1, r);
	pushup(cur);
}

void update(int cur, int L, int R, const Tag& t) {
	Info now = segt[cur];
	int l = now.l;
	int r = now.r;
	if (L <= l && r <= R) {
		segt[cur] += t;
		tag[cur] += t;
		return;
	}
	pushdown(cur);
	const int mid = (l + r) / 2;
	if (L <= mid)
		update(cur * 2, L, R, t);
	if (R > mid)
		update(cur * 2 + 1, L, R, t);
	pushup(cur);
}

Info query(int cur, int L, int R) {
	Info now = segt[cur];
	int l = now.l;
	int r = now.r;
	if (L <= l && r <= R)
		return segt[cur];
	pushdown(cur);
	const int mid = (l + r) / 2;
	if (R <= mid)
		return query(cur * 2, L, R);
	else if (L > mid)
		return query(cur * 2 + 1, L, R);
	else
		return query(cur * 2, L, R) + query(cur * 2 + 1, L, R);
}

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	
	return 0;
}