题目
描述
Suppose that the fourth generation mobile phone base stations in the Tampere area operate as follows. The area is divided into squares. The squares form an S * S matrix with the rows and columns numbered from 0 to S-1. Each square contains a base station. The number of active mobile phones inside a square can change because a phone is moved from a square to another or a phone is switched on or off. At times, each base station reports the change in the number of active phones to the main base station along with the row and the column of the matrix.
Write a program, which receives these reports and answers queries about the current total number of active mobile phones in any rectangle-shaped area.
输入
The input is read from standard input as integers and the answers to the queries are written to standard output as integers. The input is encoded as follows. Each input comes on a separate line, and consists of one instruction integer and a number of parameter integers according to the following table.
The values will always be in range, so there is no need to check them. In particular, if A is negative, it can be assumed that it will not reduce the square value below zero. The indexing starts at 0, e.g. for a table of size 4 * 4, we have 0 <= X <= 3 and 0 <= Y <= 3.
Table size: 1 * 1 <= S * S <= 1024 * 1024
Cell value V at any time: 0 <= V <= 32767
Update amount: -32768 <= A <= 32767
No of instructions in input: 3 <= U <= 60002
Maximum number of phones in the whole table: M= 2^30
输出
Your program should not answer anything to lines with an instruction other than 2. If the instruction is 2, then your program is expected to answer the query by writing the answer as a single line containing a single integer to standard output.
样例输入
0 4
1 1 2 3
2 0 0 2 2
1 1 1 2
1 1 2 -1
2 1 1 2 3
3
样例输出
3
4
来源
IOI 2001
分析与思路
贴上课的PPT截图
本题的知识点在于二位树状数组的应用,PPT中直接给出了结论所以我就直接用了,由1维到2维的推广是相似的,只是多了一次位置求和,并没有做出额外的修正处理,所以推测更高维度的树状数组只需要做类似处理就可以。
但一开始做的时候我没看到这页PPT……所以搞了个多重一维树状数组来解题,但显然查询和更新的复杂度O(mlogn)大于二维树状数组的做法O(log(m)*log(n))。所以很凉,改算法后基本没问题了
犯错点
- 还是要规避树状数组中位置0,从位置1开始使用
- 最终的结果是一个简单的集合运算
代码
#include<iostream>
using namespace std;
#pragma warning(disable:4996)
int C[1300][1300] = { 0 };
int lowbit(int x) {
return x & (-x);
}
int query(int r, int t) {
int res = 0;
for (int i = r+1; i >0 ; i-=lowbit(i))
{
for (int j = t+1; j > 0; j -= lowbit(j)) {
res += C[i][j];
}
}
return res;
}
int main() {
int x, y, l, b, r, t, s,a,u;
scanf("%d%d", &u, &s);
while (scanf("%d",&u))//大数据量情况下用scanf的时间耗费十分优秀,仅改变while()中的cin为scanf,使得时间耗费1434ms->287ms
{
if (u == 1) {
scanf("%d%d%d", &x, &y, &a);
for (int i = x+1; i <=s; i+=lowbit(i))
{
for (int j = y+1; j <= s; j += lowbit(j)) {
C[i][j] += a;
}//不用检测值是否会被减成负的(题目中说了),所以不需要记录原来的值,只做增量变更即可,可以少开一个二维数组
}
}
else if (u == 2) {
scanf("%d%d%d%d", &l, &b, &r, &t);
printf("%d\n", query( r, t)-query(r,b-1)-query(l-1,t)+query(l-1,b-1));
}
else if (u >= 3)break;
}
return 0;
}