Description
Suppose that the fourthgeneration 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 therows and columns numbered from 0 to S-1. Each square contains a base station. Thenumber of active mobile phones inside a square can change because a phone ismoved from a square to another or a phone is switched on or off. At times, eachbase station reports the change in the number of active phones to the main basestation along with the row and the column of the matrix.
Write a program, which receives these reports and answers queries about thecurrent total number of active mobile phones in any rectangle-shaped area.
Input
The input is read fromstandard input as integers and the answers to the queries are written tostandard output as integers. The input is encoded as follows. Each input comeson a separate line, and consists of one instruction integer and a number ofparameter integers according to the following table.
The values will always be in range, so there is no need to check them. Inparticular, if A is negative, it can be assumed that it will not reduce thesquare 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
Output
Your program should not answeranything 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 asingle line containing a single integer to standard output.
Sample Input
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
Sample Output
3
4
题目简介:指令0、1、2、3分别是不同的操作。输入0,S,表示,建立一个S*S的正方形网格。指令1为在(X,Y)处增加A个手机。指令2为计算L<=X<=R,B<=Y<=T的图形内共有多少手机。
方法:二维树状数组。
#include<stdio.h> int S, C[1030][1030]; int lowbit(int x) { return x & -x; }; void update(int X,int Y,int val) { int x,y; for (x = X; x<=S; x+=lowbit(x)) { for (y = Y; y<=S; y+=lowbit(y)) { C[x][y] += val; } } }; int getsum(int X, int Y) { int x, y, sum = 0; for (x=X; x>0; x-=lowbit(x)) { for (y=Y; y>0; y-=lowbit(y)) { sum += C[x][y]; } } return sum; }; int main() { int index; int X, Y, A, L, B, R, T; while(scanf("%d",&index)&&index!=3) { if(index==0) { scanf("%d",&S); continue; } if(index==1) { scanf("%d%d%d",&X,&Y,&A); update(X+1,Y+1,A); continue; } if(index==2) { scanf("%d%d%d%d",&L,&B,&R,&T); printf("%d\n",getsum(R+1,T+1) - getsum(R+1,B) - getsum(L,T+1)+getsum(L,B)); } } return 0; }