跳到正文

剪贴板

剪贴板 xdmr90xc

huashao_139
原文
剪贴板信息

剪贴板信息

发布
收录
更新

线段树 Page B-2

目录:


动态开点,就是动态地分配每个节点,具体思想是如果遍历到某个点再建立这个节点。

普通的线段树需要在维护序列前调用 build 函数,并且树的大小是线性的。
对于动态开点,不难发现其空间复杂度大约在 O(qlog⁡V)\mathrm O(q \log V) 的。实际由于 push_down 函数的影响,需要开到这个数的 22 到 33 倍。

注意:对于每个根节点,都要引用地下传。

讲完了。

试试看!

AALC001J Long Binary String

链接。

运用上面讲的东西,写就行了。

注意这里 Sgt 结构体中的 l, r 是左、右儿子,而非区间的左右端点,区间的左右端点在递归的过程中下传。

代码
C++
#include <bits/stdc++.h>

using namespace std;

#define int long long

const int N = 200010, MaxN = 1e18;

int a[N];
namespace Segment_Tree
{
	#define ls (sgt[u].l)
	#define rs (sgt[u].r)
	
	struct Sgt { int l, r, w, rev; inline void push_rev (const int &len) { rev ^= 1; w = len - w; } } sgt[160 * N];
	int idx;
	
	inline void push_up (const int &u) { sgt[u].w = sgt[ls].w + sgt[rs].w; }
	inline void push_down (const int &u, const int &len)
	{
		if (sgt[u].rev)
		{
			if (ls == 0) ls = ++idx;
			if (rs == 0) rs = ++idx;
			sgt[ls].push_rev(len - len / 2); sgt[rs].push_rev(len / 2);
			sgt[u].rev = 0;
		}
	}
	
	inline void update (int &u, const int &ql, const int &qr, const int &l, const int &r)
	{
		if (u == 0) u = ++idx;
		if (l <= ql && qr <= r) { sgt[u].push_rev(qr - ql + 1); return ; }
		push_down(u, qr - ql + 1);
		int mid = ql + qr >> 1;
		if (l <= mid) update(ls, ql, mid, l, r);
		if (r > mid)  update(rs, mid + 1, qr, l, r);
		push_up(u);
	}
	inline int query (const int &u, const int &ql, const int &qr, const int &l, const int &r)
	{
		if (u == 0) return 0;
		if (l <= ql && qr <= r) return sgt[u].w;
		push_down(u, qr - ql + 1);
		int mid = ql + qr >> 1, Ans = 0;
		if (l <= mid) Ans += query(ls, ql, mid, l, r);
		if (r > mid)  Ans += query(rs, mid + 1, qr, l, r);
		return Ans;
	}
}
using namespace Segment_Tree;

int q, rt;
signed main ()
{
//	freopen("test.in", "r", stdin);
	scanf("%lld", &q);
	while (q--)
	{
		int opt, l, r; scanf("%lld %lld %lld", &opt, &l, &r);
		if (opt == 1) update(rt, 1, MaxN, l, r);
		else printf("%lld\n", query(rt, 1, MaxN, l, r));
	}
	return 0;
}

back