hdu1754 I Hate it

来源:互联网 发布:家里的网络突然没网了 编辑:程序博客网 时间:2024/05/15 18:58

原文链接


http://acm.hdu.edu.cn/showproblem.php?pid=1754

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 61 2 3 4 5Q 1 5U 3 6Q 3 4Q 4 5U 2 9Q 1 5
 


Sample Output
5659
Hint
Huge input,the C function scanf() will work better than cin
纪念一下写的第一个线段树,没有用数组,直接用链表实现的,纠结了将近两天,终于解决了,网上大部分大神都是用数组模拟的,然后刚开始学线段树,直接看着模板敲的,最后果断RE,后来队长说是没有销毁树结点,告诉了一个比较好的方法,AC了,代码还是敲的少啊!
#include <iostream>#include <cstdio>#include <cstdlib>using namespace std;typedef struct Node{    int Left,Right;    int Max;    struct Node *LeftChild,*RightChild;}node;int score[200010];int pos;node mem[800020];inline int _max(int a,int b){    return a > b ? a : b;}node *new_tree(){    node *p = &mem[pos++];    memset(p,0,sizeof(p));    return p;}node *Build(int l,int r){    node *cur = new_tree();    cur->Left = l;    cur->Right = r;    if(l == r)    {        cur->Max = _max(score[cur->Left],score[cur->Right]);    }    else    {        int mid = (l + r)/2;        cur->LeftChild = Build(l,mid);        cur->RightChild = Build(mid + 1,r);        cur->Max = _max(cur->LeftChild->Max,cur->RightChild->Max);    }    return cur;}int Update(node *cur,int x,int num){    if(x < cur->Left || cur->Right < x)        return cur->Max;    if(cur->Left == x && cur->Right == x)    {        return cur->Max = num;    }    else    {        int a = Update(cur->LeftChild, x, num);        int b = Update(cur->RightChild, x, num);        cur->Max = _max(a,b);    }    return cur->Max;}int FindMax(node *cur,int l,int r){    if(cur->Left > r|| cur->Right < l)        return 0;    if(l <= cur->Left && cur->Right <= r)    {      return cur->Max;    }    else    {        int a = FindMax(cur->LeftChild,l,r);        int b = FindMax(cur->RightChild,l,r);        return _max(a,b);    }}int main(void){     Node *root;     int n,m,x,num,i;     char oper[2];     memset(score,0,sizeof(score));     while(scanf("%d%d",&n,&m) != EOF)     {         for(i = 1;i <= n;i++)         {            scanf("%d",&score[i]);         }        root = Build(1,n);        pos = 0;        while(m--)        {            scanf("%s%d%d",oper,&x,&num);            if(oper[0] == 'Q')            {                printf("%d\n",FindMax(root,x,num));            }            else            {                score[x] = num;                Update(root,x,num);            }        }     }    return 0;}

0 0
原创粉丝点击