hdu 1754 I Hate It (線段樹)

小飛_Xiaofei發表於2013-12-06

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

Author
linle


Solution

以下部分的版權歸本人(小飛)所有。所有權利保留。

歡迎轉載,轉載時請註明出處:

http://blog.csdn.net/xiaofei_it/article/details/17173453

#include <stdio.h>
#define MAX 300000
struct Node
{
	int l,r,max;
};
int n,m,s[MAX],i,A,B;
char c;
struct Node a[MAX*10];

int max(int a,int b)
{
	if (a>b)
		return a;
	else
		return b;
}

void create(int root,int l,int r)
{
	int mid;
	a[root].l=l;a[root].r=r;
	if (l==r)
	{
		a[root].max=s[l];
		return;
	}
	mid=(l+r)/2;
	create(root*2,l,mid);
	create(root*2+1,mid+1,r);
	a[root].max=max(a[root*2].max,a[root*2+1].max);
}

int query(int r,int A,int B)
{
	int mid;
	if (B<a[r].l||a[r].r<A)
		return 0;
	if (A<=a[r].l&&a[r].r<=B)
		return a[r].max;
	return max(query(r*2,A,B),query(r*2+1,A,B));
}

void update(int r,int p)
{
	if (p<a[r].l||a[r].r<p)
		return;
	if (p==a[r].l&&p==a[r].r)
	{
		a[r].max=s[p];
		return;
	}
	update(2*r,p);
	update(2*r+1,p);
	a[r].max=max(a[r*2].max,a[r*2+1].max);
}

int main()
{
	while (scanf("%d%d",&n,&m)!=EOF)
	{
		for (i=1;i<=n;i++) scanf("%d",s+i);
		create(1,1,n);
		while (m--)
		{
			getchar();
			scanf("%c%d%d",&c,&A,&B);
			if (c=='Q')
				printf("%d\n",query(1,A,B));
			else
			{
				s[A]=B;
				update(1,A);
			}
		}
	}
	return 0;
}



 

相關文章