HDU-1892 See you~
二维树状数组的模板题了,初始化的时候注意下,不用逐个插入,而是直接用lowbit这个函数。
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define MAX 1005 int c[MAX][MAX];; inline int lowbit( int x ) { return x & -x; } inline void modify( int x, int y, int val ) { for( int i = x; i <= 1001; i += lowbit( i ) ) { for( int j = y; j <= 1001; j += lowbit( j ) ) c[i][j] += val; } } inline int getsum( int x, int y ) { int sum = 0; for( int i = x; i > 0; i -= lowbit( i ) ) { for( int j = y; j > 0; j -= lowbit( j ) ) sum += c[i][j]; } return sum; } inline void swap( int &x, int &y ) { int temp = x; x = y; y = temp; } inline int finalsum( int x1, int y1, int x2, int y2 ) { return getsum(x2, y2)-getsum(x1-1, y2)-getsum(x2, y1-1)+getsum(x1-1, y1-1); } inline void getint( int &t ) { char c; while( c= getchar(), c< '0'|| c> '9' ) ; t= c- '0'; while( c= getchar(), c>= '0'&& c<= '9' ) { t= t* 10+ c- '0'; } } int main( ) { int T, N, x1, y1, x2, y2, val, sum; char op[10]; getint( T ); for( int cas = 1; cas <= T; ++cas ) { printf( "Case %d:\n", cas ); for( int i = 1; i <= 1001; ++i ) { for( int j = 1; j <= 1001; ++j ) { c[i][j] = lowbit( i ) * lowbit( j ); } } scanf( "%d", &N ); while( N-- ) { scanf( "%s", op ); if( op[0] == 'A' ) { // scanf( "%d%d%d", &x1, &y1, &val ); getint( x1 ), getint( y1 ), getint( val ); x1++, y1++; modify( x1, y1, val ); } else if( op[0] == 'D' ) { // scanf( "%d%d%d", &x1, &y1, &val ); getint( x1 ), getint( y1 ), getint( val ); x1++, y1++; sum = finalsum( x1, y1, x1, y1 ); if( val > sum ) val = sum; modify( x1, y1, -val ); } else if( op[0] == 'M' ) { // scanf( "%d%d%d%d%d", &x1, &y1, &x2, &y2, &val ); getint( x1 ), getint( y1 ); getint( x2 ), getint( y2 ), getint( val ); x1++, y1 ++, x2++, y2++; sum = finalsum( x1, y1, x1, y1 ); if( val > sum ) val = sum; modify( x1, y1, -val ); modify( x2, y2, val ); } else { // scanf( "%d%d%d%d", &x1, &y1, &x2, &y2 ); getint( x1 ), getint( y1 ); getint( x2 ), getint( y2 ); x1++, y1++, x2++, y2++; if( x1 > x2 ) swap( x1, x2 ); if( y1 > y2 ) swap( y1, y2 ); printf( "%d\n", finalsum( x1, y1, x2, y2 ) ); } } } return 0; }