【图论07】线段树 1002 I Hate It

本文深入探讨了线段树算法的原理、实现及在实际问题中的应用,包括模板介绍、初始化、查询和更新操作,通过具体示例展示了如何高效解决区间查询和修改问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法思路:线段树。

代码如下:

//模板开始
#include <string>   
#include <vector>   
#include <algorithm>   
#include <iostream>   
#include <sstream>   
#include <fstream>   
#include <map>   
#include <set>   
#include <cstdio>   
#include <cmath>   
#include <cstdlib>   
#include <ctime>
#include <iomanip>
#include <queue>
#include <string.h>
#define SZ(x) (int(x.size()))
using namespace std;

int toInt(string s){
	istringstream sin(s); 
	int t; 
	sin>>t; 
	return t;
}
template<class T> string toString(T x){
	ostringstream sout; 
	sout<<x; 
	return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
	istringstream sin(s); 
	int64 t; 
	sin>>t;
	return t;
}
template<class T> T gcd(T a, T b){ 
	if(a<0) 
		return gcd(-a, b);
	if(b<0) 
		return gcd(a, -b);
	return (b == 0)? a : gcd(b, a % b);
}

#define LOCAL
//模板结束(通用部分)

#define MAXN 200005 * 4

int maxv[MAXN];
int ql, qr;
int p, v;
int T1, T2;
int zhishu;

int query(int o, int L, int R)
{
	int M = L + (R - L) / 2, ans = 0;
	if(ql <= L && R <= qr)
	{
		return maxv[o];
	}
	if(ql <= M)
	{
		ans = max(ans, query(o * 2, L, M));
	}
	if(M < qr)
	{
		ans = max(ans, query(o * 2 + 1, M + 1, R));
	}
	return ans;
}

void update1(int o, int L, int R)
{
	int M = L + (R - L) / 2;
	if(L == R)
	{
		maxv[o] = v;
	}
	else
	{
		if(p <= M)
		{
			update1(o * 2, L, M);
		}
		else
		{
			update1(o * 2 + 1, M + 1, R);
		}
		maxv[o] = max(maxv[o * 2], maxv[o * 2 + 1]); 
	}
}

void init()
{
	zhishu = 0;
	while((1<<zhishu) < T1)
	{
		zhishu++;
	}
	int up_max = (1<<(zhishu + 1)) - 1;
	int chuzhi = 1<<(zhishu);
	for(int i = chuzhi; i <= chuzhi + T1 - 1; i++)
	{
		//cin>>sum[i];
		scanf("%d", &maxv[i]);
	}
	for(int i = chuzhi + T1; i <= up_max; i++)
	{
		maxv[i] = 0;
	}
	for(int i = (1<<zhishu) - 1; i >= 1; i--)
	{
		maxv[i] = max(maxv[i * 2], maxv[i * 2 + 1]);
	}
}

int main()
{
#ifdef LOCAL
	//freopen("shuju.txt", "r", stdin);
#endif

	char a[10];
	int b, c;
	//cin>>T1>>T2;
	while(scanf("%d%d", &T1, &T2) == 2)
	{
		init();		
		for(int i = 0; i < T2; i++)
		{
			//cin>>a>>b>>c;
			scanf("%s", a);
			scanf("%d%d", &b, &c);
			if(a[0] == 'Q')
			{
				ql = b;
				qr = c;
				cout<<query(1, 1, 1<<zhishu)<<endl;
			}
			if(a[0] == 'U')
			{
				p = b;
				v = c;
				update1(1, 1, 1<<zhishu);
			}
		}
	}

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值