HDU 1754 线段树

线段树单点更新

这道题需要注意的是输入,题目明确提示了要用scanf来输入加快速度,所以这里可能会有一个错误,在build里面是用scanf输入的。而输入文件可能是在输入N个数据后有一个换行符,如果不把换行符读出来可能会有错误。所以要用下面这句话

scanf("%*c%c%d %d", &c, &a, &b);
#include
#include
#include
using namespace std;
int N, M;
#define maxn 200010
#define Lchild rt<<1,L,m
#define Rchild rt<<1|1,m+1,R
#define MAX(a,b) a>b?a:b
int SegmentTree[maxn * 3];
void push_up(int rt)
{
	SegmentTree[rt] = MAX(SegmentTree[rt << 1], SegmentTree[rt << 1 | 1]);
}
void build(int rt=1,int L=1,int R=N)
{
	if (L == R)
	{
		//cin >> SegmentTree[rt];
		scanf_s("%d", &SegmentTree[rt]);
		return;
	}
	int m = (L + R) >> 1;
	build(Lchild);
	build(Rchild);
	push_up(rt);
}
void update(int p, int delta, int rt = 1, int L = 1, int R = N)
{
	if (L == R)
	{
		SegmentTree[rt] = delta;
		return;
	}
	int m = (L + R) >> 1;
	if (p <= m)
		update(p, delta, Lchild);
	else
		update(p, delta, Rchild);
	push_up(rt);
}
int query(int l, int r, int rt = 1, int L = 1, int R = N)
{
	if (l <= L&&R <= r)
	{
		return SegmentTree[rt];
	}
	int m = (L + R) >> 1;
	int ret = -1;
	if (l <= m)
	{
		int temp = query(l, r, Lchild);
		ret = MAX(ret, temp);
	}
	if (r > m)
	{
		int te = query(l, r, Rchild);
		ret = MAX(ret,te);
	}
	return ret;
}
int main()
{
	while (cin>>N>>M)
	{
		build();
		char c;
		int a, b;
		for (int i = 1; i <= M; i++)
		{
			//cin >> c >> a >> b;
			scanf("%*c%c%d %d", &c, &a, &b);
			
			if (c == 'Q')
			{
				cout << query(a, b) << endl;
			}
			else if (c == 'U')
			{
				update(a, b);
			}
		}
	}
}

你可能感兴趣的:(线段树)