HDU 1754 ——简单线段树

题意如下:

给你从1到N 每个学生的成绩。 有M个操作,操作分为两种,一种是查询Q X Y(查询从X学生到Y学生的最高分数) 另一种就是U X Y(将学生X的成绩改为Y);

一道明显的线段树题目 ,过程也是比较明确,建树、查询最大值、更新树.


附上代码:

#include <stdio.h>
#include <iostream>
#include <cstring>

#define max(x,y) (x>y?x:y)



//定义节点结构体
typedef struct
{
	int Max;
	int left,right;

}Node;

int sc[200010];
Node tree[4000200];

int  build(int root,int left,int right)
{       int mid;
		tree[root].left=left;
		tree[root].right=right;

		if(left==right)//如果该节点的左右端点相等 则代表已经到了底端 所以该节点的最大值为已经输入的值
		{
			return tree[root].Max=sc[left];
		}

		mid=(left+right)/2;
		int a,b;
		 a=build(2*root,left,mid);
		 b=build(2*root+1,mid+1,right);
		return tree[root].Max=max(a,b);

}

//更新树的pos节点 将其的分数改为score 并且更新所有的Max
int  update(int root,int pos,int score)
{
	if(tree[root].left>pos || tree[root].right<pos ) return tree[root].Max;

	if(tree[root].left==pos && tree[root].right==pos )	return tree[root].Max=score;

	int a,b;
	a=update(2*root,pos,score);
	b=update(2*root+1,pos,score);
	tree[root].Max=max(a,b);
	return tree[root].Max;
}

int findmax(int root,int left,int right)
{
	if(right<tree[root].left || left>tree[root].right) return 0;
	if(left<=tree[root].left&&right>=tree[root].right) return tree[root].Max;

	int a=findmax(2*root,left,right);
	int b=findmax(2*root+1,left,right);

	return max(a,b);

}

int main()
{
	//freopen("in.in","r",stdin);
	int N,M;
	while(scanf("%d %d",&N,&M)!=EOF)
	{
			for(int i=1;i<=N;i++)
				scanf("%d",&sc[i]);
			build(1,1,N);

			for(int i=1;i<=M;i++){getchar () ;
				char ch;
				int a,b;
				scanf("%c %d %d",&ch,&a,&b);
				if(ch=='U')
				{	sc[a]=b;
					update(1,a,b);
				}
				if(ch=='Q')
				{
					printf("%d\n",findmax(1,a,b));
				}
			}
	}

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值