hdu-2642 Stars---二维树状数组(细节处理)

题目链接:

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, int y, 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 }

 

posted @ 2018-04-26 21:51  _努力努力再努力x  阅读(148)  评论(0编辑  收藏  举报