hdu 1754 线段树结构体

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct tree//线段树构造体
{
	int a,b,max;
	tree *left;
	tree *right;
	tree():a(0),b(0),max(0){left=NULL;right=NULL;}
};

tree *construct()//构造头结点
{
     tree * head = new tree();
	 return head;
}
inline int maxx(int a,int b)//返回两数中最大的值
{
	return a>b?a:b;
}
void del(tree *head)//删除线段树
{
	if(head==NULL) return;
	del(head->left);
	del(head->right);
	delete(head);
}

tree *perfect(int a,int b)//创建空值型线段树
{
    tree * head = construct();
	if(a+1==b)
	{
        head->a=a;
		head->b=b;
	}
	else
	{  
		head->a = a;
		head->b = b;
	    int mid = (a+b)/2;
		head->left = perfect(a,mid);
		head->right = perfect(mid,b);
	}
	return head;
}

void update(tree *head,int a,int b)//更新结点值
{
	if(head->a==a&&head->b==a+1)
	{
		head->max = b; return ;
	}
	if(a<head->left ->b) update(head->left,a,b);
	else update(head->right ,a,b);
	head->max = maxx(head->left ->max ,head->right ->max);
	return ;
}

void insert(tree *head,int a,int b)//插入结点值,比更新会少点内存,同样可以用更新
{
	if(head->a==a&&head->b==a+1)
	{
		head->max=b;return ;
	}
	if(b>head->max) head->max = b;
	if(a<head->left->b) {insert(head->left ,a,b);}
	else insert(head->right ,a,b);
	return ;
}

int query(tree *head,int a,int b)//询问
{
	if(head->a==a&&head->b==b) return head->max;
	if(b<=head->left ->b) return query(head->left ,a,b);
	else if(a>=head->right ->a) return query(head->right ,a,b);
	else 
		return maxx(query(head->left ,a,head->left ->b),query(head->right,head->right->a,b));
}

void init()
{
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		tree *head = perfect(1,n+1);

		for(int i=1;i<=n;i++)
		{
			int temp;
			scanf("%d",&temp);
			insert(head,i,temp);
		}

		char c;
		int x,y;
		for(int i=1;i<=m;i++)
		{
			getchar();
			scanf("%c%d%d",&c,&x,&y);
			if(c=='Q')
				printf("%d\n",query(head,x,y+1));
			else
				update(head,x,y);
		}
		del(head);
	}
	return ;
}
int main()
{
    init();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值