首页 > 代码库 > hdu 1166 敌兵布阵

hdu 1166 敌兵布阵

标准的树状数组模板题,需要注意的是树状数组的初始节点的编号为1。

 1 #define     MAX_N 1000007 2 #include <cstdlib> 3 #include  <cstdio> 4 #include  <iostream> 5 #include <cstring> 6 using namespace std; 7 int bit[MAX_N+1], n; 8 int lowbit(int x) 9 {10     return x&(-x);11 }12 int sum(int i)13 {14     int s = 0;15     while( i > 0 )16     {17         s += bit[i];18         i -= lowbit(i);19     }20     return s;21 }22 void add(int i , int x)23 {24     while( i <= n )25     {26         bit[i] += x;27         i += lowbit(i);28     }29 }30 int main(int argc, char *argv[])31 {32     int T;33     int c = 1;34     scanf ( "%d", &T );35     while( T-- )36     {37         scanf("%d", &n);38         memset(bit, 0, sizeof(bit));39         for( int i = 1 ; i <= n ; i++ )40         {41             int tmp;42             scanf ( "%d", &tmp );43             add(i, tmp);44         }45         char s[10];46         int a, b;47         printf("Case %d:\n", c++);48         while(1)49         {50             scanf("%s", s);51             if( !strcmp(s , "End" ))52             {53                 break;54             }55             else56             {57                 scanf("%d%d", &a, &b);58                 if( !strcmp(s,  "Query") )59                 {60                     printf("%d\n", sum(b) - sum(a-1));61                 }62                 else if(!strcmp( s ,  "Add") )63                 {64                     add(a, b);65                 }66                 else if(!strcmp(s, "Sub"))67                 {68                     add(a, -b);69                 }70             }71         }72     }73 }

 

hdu 1166 敌兵布阵