hdu-2642 Stars---二維樹狀數組(細節處理)
阿新 • • 發佈:2018-04-27
else oid ios esp ble hdu .cn ans AS
題目鏈接:
http://acm.hdu.edu.cn/showproblem.php?pid=2642
題目大意:
B x y:將星星x y點亮
D x y:將星星x y熄滅
Q x1 x2 y1 y2:詢問該區域內有多少亮的星
解題思路:
二維樹狀數組模擬即可
註意:
1、下標+1
2、同一位置星星可以點亮多次,熄滅多次,需要用bool數組記錄星星狀態再更改樹狀數組
3、輸入的區域是x1 x2 y1 y2,一開始錯認為是x1 y1 x2 y2,而且沒有大小順序,需要自己判斷
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4#include<string> 5 #include<map> 6 #include<set> 7 #include<cmath> 8 #include<algorithm> 9 #include<vector> 10 #include<sstream> 11 #define lowbit(i) (i&(-i)) 12 using namespace std; 13 int star[1005][1005]; 14 bool light[1005][1005]; 15 16 void add(int x, inty, int d) 17 { 18 for(int i = x; i <= 1005; i += lowbit(i)) 19 { 20 for(int j = y; j <= 1005; j += lowbit(j)) 21 star[i][j] += d; 22 } 23 } 24 int sum(int x, int y) 25 { 26 int ans = 0; 27 for(int i = x; i; i -= lowbit(i)) 28 { 29 for(int j = y; j; j -= lowbit(j))30 ans += star[i][j]; 31 } 32 return ans; 33 } 34 int main() 35 { 36 int n, x, y, x1, x2, y1, y2; 37 while(scanf("%d", &n) != EOF) 38 { 39 memset(light, 0, sizeof(light)); 40 memset(star, 0, sizeof(star)); 41 char c[5]; 42 while(n--) 43 { 44 scanf("%s", c); 45 if(c[0] == ‘B‘) 46 { 47 scanf("%d%d", &x, &y); 48 x++, y++; 49 if(!light[x][y])add(x, y, 1); 50 light[x][y] = 1; 51 } 52 else if(c[0] == ‘D‘) 53 { 54 scanf("%d%d", &x, &y); 55 x++, y++; 56 if(light[x][y])add(x, y, -1); 57 light[x][y] = 0; 58 } 59 else if(c[0] == ‘Q‘) 60 { 61 scanf("%d%d%d%d", &x1, &x2, &y1, &y2); 62 x1++, y1++, x2++, y2++; 63 if(x1 > x2)swap(x1, x2); 64 if(y1 > y2)swap(y1, y2); 65 cout<<(sum(x2, y2) + sum(x1 - 1, y1 - 1) - sum(x1 - 1, y2) - sum(x2, y1 - 1))<<endl; 66 } 67 } 68 } 69 return 0; 70 }
hdu-2642 Stars---二維樹狀數組(細節處理)