[JSOI2009]计数问题 二维树状数组

~~~题面~~~

题解:

二维树状数组的板子题,,,学了这么久第一次写二维树状数组,惭愧啊。

怎么写就不说了,看代码吧。

跟普通的是一样的写法

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define R register int
 4 #define AC 302
 5 #define lowbit(x) (x & (-x))
 6 int n, m, k;
 7 int a[AC][AC], c[AC][AC][AC];
 8 
 9 inline int read()
10 {
11     int x = 0;char c = getchar();
12     while(c > '9' || c < '0') c = getchar();
13     while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
14     return x; 
15 }
16 
17 inline void add(int x, int y, int w, int h)
18 {
19     for(R i = x; i <= n; i += lowbit(i))
20         for(R j = y; j <= m; j += lowbit(j))
21             c[i][j][w] += h; 
22 }
23 
24 inline int search(int x, int y, int w)
25 {
26     int ans = 0;
27     if(! x || !y || x > n || y > m) return 0;
28     for(R i = x; i ; i -= lowbit(i))
29         for(R j = y; j ; j -= lowbit(j))
30             ans += c[i][j][w];
31     return ans;
32 }
33 
34 void pre()
35 {
36     n = read(), m = read();
37     for(R i = 1; i <= n; i++)
38         for(R j = 1; j <= m; j++)
39         {
40             a[i][j] = read();
41             add(i, j, a[i][j], 1);//建立树状数组
42         }
43 }
44 
45 void work()
46 {
47     int opt, x1, x2, x3, x4, x5, tmp;
48     k = read();
49     for(R i = 1; i <= k; i++)
50     {
51         opt = read();
52         if(opt == 1)
53         {
54             x1 = read(), x2 = read(), x3 = read();
55             if(x3 != a[x1][x2])
56             {
57                 add(x1, x2, a[x1][x2], -1);//消除原有的值
58                 add(x1, x2, x3, 1);//新增值
59                 a[x1][x2] = x3;
60             }
61         }
62         else
63         {
64             x1 = read(), x3 = read(), x2 = read(), x4 = read(), x5 = read();
65             tmp = search(x3, x4, x5) - search(x3, x2 - 1, x5) - search(x1 - 1, x4, x5) + search(x1 - 1, x2 - 1, x5);//error,,,-1啊
66             printf("%d\n", tmp);
67         }
68     }
69 }
70 
71 int main()
72 {
73 //    freopen("in.in", "r", stdin);
74     pre();
75     work();
76 //    fclose(stdin);
77     return 0;
78 }

猜你喜欢

转载自www.cnblogs.com/ww3113306/p/9249796.html