hdu1754 I Hate It (线段树 更新点的值)

I Hate It

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 51089    Accepted Submission(s): 20037


Problem Description
非常多学校流行一种比較的习惯。

老师们非常喜欢询问。从某某到某某其中,分数最高的是多少。
这让非常多学生非常反感。

无论你喜不喜欢。如今须要你做的是,就是依照老师的要求,写一个程序,模拟老师的询问。当然。老师有时候须要更新某位同学的成绩。

 

Input
本题目包括多组測试。请处理到文件结束。
在每一个測试的第一行。有两个正整数 N 和 M ( 0<N<=200000,0<M<5000 ),分别代表学生的数目和操作的数目。


学生ID编号分别从1编到N。


第二行包括N个整数,代表这N个学生的初始成绩,当中第i个数代表ID为i的学生的成绩。
接下来有M行。

每一行有一个字符 C (仅仅取'Q'或'U') ,和两个正整数A,B。
当C为'Q'的时候,表示这是一条询问操作,它询问ID从A到B(包含A,B)的学生其中。成绩最高的是多少。
当C为'U'的时候,表示这是一条更新操作,要求把ID为A的学生的成绩更改为B。

 

Output
对于每一次询问操作,在一行里面输出最高成绩。
 

Sample Input
5 6 1 2 3 4 5 Q 1 5 U 3 6 Q 3 4 Q 4 5 U 2 9 Q 1 5
 

Sample Output
5 6 5 9
Hint
Huge input,the C function scanf() will work better than cin
 

Author
linle
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  1166 1698 1542 1394 2795 
 

Statistic | Submit | Discuss | Note

看到那么多的查找次数用线段树无疑了。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct node
{
	int left,right,val;
}c[200000*3];
void build_tree(int l,int r,int root)//建树
{
	c[root].left=l;
	c[root].right=r;
	if(l==r)
	{
		scanf("%d",&c[root].val);
		return ;
	}
	int mid=(c[root].left+c[root].right)/2;
	build_tree(l,mid,root*2);
	build_tree(mid+1,r,root*2+1);
	c[root].val=max(c[root*2].val,c[root*2+1].val);
}
void search_tree(int l,int r,int root,int &Max)//查找
{
	if(c[root].left==l&&c[root].right==r)
	{
		Max=c[root].val;
		return ;
	}
	int mid=(c[root].left+c[root].right)/2;
	if(mid<l)
	search_tree(l,r,root*2+1,Max);
	else if(mid>=r)
	search_tree(l,r,root*2,Max);
	else
	{
		int Max1;
		search_tree(l,mid,root*2,Max);
		search_tree(mid+1,r,root*2+1,Max1);
		Max=max(Max,Max1);
	}
}
void update_tree(int pos,int root,int x)//更新点
{
	if(c[root].left==c[root].right&&c[root].left==pos)
	{
		c[root].val=x;
		return ;
	}
	int mid=(c[root].left+c[root].right)/2;
	if(mid<pos)
	update_tree(pos,root*2+1,x);
	else
	update_tree(pos,root*2,x);
	c[root].val=max(c[root*2].val,c[root*2+1].val);
}
int main()
{
	int n,m;
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		memset(&c,0,sizeof(&c));
		build_tree(1,n,1);
		getchar();
		for(int i=0;i<m;i++)
		{
			char ch;
			scanf("%c",&ch);
			if(ch=='Q')
			{
				int a,b,Max;
				scanf("%d %d",&a,&b);
				getchar();
				if(a<b)
				search_tree(a,b,1,Max);
				else
				search_tree(b,a,1,Max);
				printf("%d
",Max);
			}
			if(ch=='U')
			{
				int a,b;
				scanf("%d %d",&a,&b);
				getchar();
				update_tree(a,1,b);
			}
		}
	}
	return 0;
}


原文地址:https://www.cnblogs.com/zsychanpin/p/7326118.html