[线段树] HDU1166


标准的更新一段区间的和啦

线段树讲解:http://www.cnblogs.com/TenosDoIt/p/3453089.html

百度搜索的第一个还是很好哒hhh

写的特别详细(就是喜欢这样的blog23333)


这里没用到传说中的区间更新,看起来还能简单一点hhh


#include 
#include 
#include 
#define n 50005 << 2
#define lson root * 2     //数组中的左孩子
#define rson root * 2 + 1 //数组中的右孩子

using namespace std;

int Tree[ n ]; //线段树(递归)

//建立树
void build ( int root, int st, int end ) {
        if ( st == end ) //叶子节点
                scanf ( "%d", &Tree[ root ] );
        else {
                int mid = ( st + end ) / 2;
                build ( lson, st, mid );      //左孩子
                build ( rson, mid + 1, end ); //右孩子
                Tree[ root ] = Tree[ lson ] + Tree[ rson ];
        }
}

//计算和;
// st,end是所求范围;ST,END是当前搜索到的范围
int query ( int root, int ST, int END, int st, int end ) {
        if ( st > END || end < ST ) //不在范围内
                return 0;
        if ( st <= ST && end >= END ) //完全在范围里
                return Tree[ root ];
        int mid = ( ST + END ) / 2;
        return query ( lson, ST, mid, st, end ) + query ( rson, mid + 1, END, st, end );
}

//更新叶子节点的值
// indx是建树之前,在原数组里的位置
void update ( int root, int st, int end, int indx, int val ) {
        if ( st == end ) {
                if ( st == indx )
                        Tree[ root ] += val;
                return;
        }

        int mid = ( st + end ) / 2;
        if ( indx <= mid ) //向左搜索(要有等号)
                update ( lson, st, mid, indx, val );
        else
                update ( rson, mid + 1, end, indx, val ); //向右搜索
        Tree[ root ] = Tree[ lson ] + Tree[ rson ];
}

int main () {
        int T;
        scanf ( "%d", &T );
        for ( int i = 1; i <= T; i++ ) {
                printf ( "Case %d:\n", i );
                int N;
                scanf ( "%d", &N );

                memset ( Tree, 0, sizeof ( Tree ) );
                build ( 1, 1, N );

                char instruct[ 8 ];
                while ( ~scanf ( "%s", &instruct ) ) {

                        if ( instruct[ 0 ] == 'E' )
                                break;

                        int a, b;
                        scanf ( "%d%d", &a, &b );

                        if ( instruct[ 0 ] == 'Q' )
                                printf ( "%d\n", query ( 1, 1, N, a, b ) );
                        else if ( instruct[ 0 ] == 'A' )
                                update ( 1, 1, N, a, b );
                        else if ( instruct[ 0 ] == 'S' )
                                update ( 1, 1, N, a, -b );
                }
        }
        return 0;
}


你可能感兴趣的:(ACM)