1. 程式人生 > >hdu1754 I hate it (線段樹)

hdu1754 I hate it (線段樹)

文件 build dash ota pan pos 最大 eps track

I Hate It

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

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

HintHuge input,the C function scanf() will work better than cin 

Author linle
分析:線段樹入門基礎題。每次更新結點存儲該以結點為根的子樹中最大值。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
#define ll long long
#define CL(a,b) memset(a,b,sizeof(a))
#define MAXN 800010

struct node
{
    int a,b,r;
}t[MAXN];
int n,m,ans;

void build(int x, int y, int num)
{
    t[num].a = x;
    t[num].b = y;
    t[num].r = 0;
    if(x == y) return ;
    int mid = (x+y)/2;
    build(x, mid, num*2);
    build(mid+1, y, num*2+1);
}

void update(int x, int y, int num)
{
    if (t[num].a == t[num].b && t[num].b == x)
    {
        t[num].r = y;
        return ;
    }
    int mid = (t[num].a+t[num].b)/2;
    if(x > mid) update(x, y, num*2+1);
    else update(x, y, num*2);
    t[num].r = max(t[num*2].r, t[num*2+1].r);
}

void query(int x, int y, int num)
{
     if(t[num].a == x && t[num].b == y)
     {
         ans = max(ans, t[num].r);
         return ;
     }
     int mid = (t[num].a+t[num].b)/2;
     if(x >= mid+1) query(x, y, num*2+1);
     else if(y <= mid) query(x, y, num*2);
     else
     {
         query(x, mid, num*2);
         query(mid+1, y, num*2+1);
     }
}

int main()
{
    char ch;
    int x,y,k;
    while(scanf("%d%d",&n,&m)==2)
    {
        build(1, n, 1);
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&k);
            update(i, k, 1);
        }

        while(m--)
        {
            getchar();
            scanf("%c%d%d",&ch,&x,&y);
            if(ch == ‘U‘)
            {
                update(x, y, 1);
            }
            else if(ch == ‘Q‘)
            {
                ans = -99999;
                query(x, y, 1);
                printf("%d\n",ans);
            }
        }
    }
    return 0;
}


hdu1754 I hate it (線段樹)