跳到正文

剪贴板

剪贴板 kszxwo4r

huashao_139
原文
剪贴板信息

剪贴板信息

发布
收录
更新

线段树 Page B-1

目录:


普通二分显然是 O(log⁡2n)\mathrm O(\log^2 n) 的。

线段树二分,顾名思义,就是在线段树上二分。

由于线段树具有在每个节点二叉的特点,所以在每个节点可以用一种和二分类似的方法向左、右子节点移动。


以 AALC001C 为例,本题需要你第一个前、后缀和不小于 tt 的位置。

再以前缀和为例,如果父节点的权值和都小于 tt,那就可以直接返回。
否则如果左子结点的权值和小于 tt,查询右子节点,否则查询左子结点。

那么不难写出代码。

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

using namespace std;

#define int long long

const int N = 200010;

int a[N];
namespace Segment_Tree
{
	#define ls ((u) << 1)
	#define rs ((u) << 1 | 1)
	
	struct Sgt { int l, r, w; } sgt[4 * N];
	inline void push_up (const int &u) { sgt[u].w = sgt[ls].w + sgt[rs].w; }
	
	inline void build (const int &u, const int &l, const int &r)
	{
		sgt[u] = (Sgt) { l, r, a[l] };
		if (l == r) return ;
		int mid = l + r >> 1;
		build(ls, l, mid); build(rs, mid + 1, r);
		push_up(u);
	}
	inline void update (const int &u, const int &x, const int &k)
	{
		if (sgt[u].l == sgt[u].r) { sgt[u].w = k; return ; }
		int mid = sgt[u].l + sgt[u].r >> 1;
		if (x <= mid) update(ls, x, k);
		if (x > mid)  update(rs, x, k);
		push_up(u);
	}
	inline int query (const int &u, const int &l, const int &r)
	{
		if (l <= sgt[u]. l && sgt[u].r <= r) return sgt[u].w;
		int mid = sgt[u].l + sgt[u].r >> 1, sum = 0;
		if (l <= mid) sum += query(ls, l, r);
		if (r > mid)  sum += query(rs, l, r);
		return sum;
	}
	inline int getl (const int &u, const int &x)
	{
		if (x > sgt[u].w) return sgt[u].r + 1;
		if (sgt[u].l == sgt[u].r) return sgt[u].l;
		if (x > sgt[ls].w) return getl(rs, x - sgt[ls].w);
		else return getl(ls, x);
	}
	inline int getr (const int &u, const int &x)
	{
		if (x > sgt[u].w) return sgt[u].l - 1;
		if (sgt[u].l == sgt[u].r) return sgt[u].l;
		if (x > sgt[rs].w) return getr(ls, x - sgt[rs].w);
		else return getr(rs, x);
	}
}
using namespace Segment_Tree;

int n, q;
signed main ()
{
//	freopen("test.in", "r", stdin);
	scanf("%lld %lld", &n, &q);
	for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
	
	build(1, 1, n);
	while (q--)
	{
		int opt; scanf("%lld", &opt);
		if (opt == 1)
		{
			int i, x; scanf("%lld %lld", &i, &x);
			update(1, i, x);
		}
		else if (opt == 2)
		{
			int l, t; scanf("%lld %lld", &l, &t);
			if (l > 1) t += query(1, 1, l - 1);
			printf("%lld\n", getl(1, t));
		}
		else
		{
			int l, t; scanf("%lld %lld", &l, &t);
			if (l < n) t += query(1, l + 1, n);
			printf("%lld\n", getr(1, t));
		}
	}
	return 0;
}

back