HDU 1754 I Hate it 线段树

  题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1754

  题目大意: 给一串儿数, 要求求出区间最大值

  解题思路: 同样是最基础的东西, 单点更新和查询

  代码: 

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <map>
#include <cstring>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <stack>
#include <deque>
#include <map>

#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1

const int maxn = 200000+7;
using namespace std;
int tree[4*maxn];
int arr[maxn];
char op[10];

void pushPlus( int rt ) {
    tree[rt] = max( tree[rt<<1], tree[rt<<1|1] );
}

void build( int l, int r, int rt ) {
    if( l == r ) {
        tree[rt] = arr[l];
        return;
    }
    int m = (l + r) >> 1;
    build(lson);
    build(rson);
    pushPlus(rt);
}

int Query( int L, int R, int l, int r, int rt ) {
    if( L <= l && R >= r ) {
        return tree[rt];
    }
    int m = (l + r) >> 1;
    int ret = 0;
    if( L <= m ) ret = max( ret, Query(L, R, lson) );
    if( R > m ) ret = max( ret, Query(L, R, rson) );
    return ret;
}

void Update( int p, int add, int l, int r, int rt ) {
    if( l == r ) {
        tree[rt] = add;
        return;
    }
    int m = (l + r) >> 1;
    if( p <= m ) Update(p, add, lson );
    else  Update(p, add, rson );
    pushPlus(rt);
}

int main() {
    int n, mm;
    while( scanf( "%d%d", &n, &mm ) == 2 ) {
        for( int i = 1; i <= n; i++ ) {
            scanf( "%d", &arr[i] );
        }
        build(1, n, 1);
        
        for( int j = 1; j <= mm; j++ ) {
            int a, b;
            scanf( "%s%d%d", op, &a, &b );
            getchar();
            if( op[0] == 'Q' ) {
                printf( "%d
", Query(a, b, 1, n, 1) );
            }
            else {
                Update( a, b, 1, n, 1 );
            }
        }
    }
}
View Code

  思考: 有时候看着挺简单但是写着还是需要一定时间的, 上次写这道题的时候我是直接抄的板子, 这次我是自己写的, 该练练自己的代码能力了

原文地址:https://www.cnblogs.com/FriskyPuppy/p/7285718.html