POJ 1656 Counting Black

Counting Black
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 6578   Accepted: 4229

Description

There is a board with 100 * 100 grids as shown below. The left-top gird is denoted as (1, 1) and the right-bottom grid is (100, 100). 
POJ 1656 Counting Black_第1张图片
We may apply three commands to the board: 

1. WHITE x, y, L // Paint a white square on the board,
// the square is defined by left-top grid (x, y)
// and right-bottom grid (x+L-1, y+L-1)

2. BLACK x, y, L // Paint a black square on the board,
// the square is defined by left-top grid (x, y)
// and right-bottom grid (x+L-1, y+L-1)

3. TEST x, y, L // Ask for the number of black grids
// in the square (x, y)- (x+L-1, y+L-1)

In the beginning, all the grids on the board are white. We apply a series of commands to the board. Your task is to write a program to give the numbers of black grids within a required region when a TEST command is applied. 

Input

The first line of the input is an integer t (1 <= t <= 100), representing the number of commands. In each of the following lines, there is a command. Assume all the commands are legal which means that they won't try to paint/test the grids outside the board.

Output

For each TEST command, print a line with the number of black grids in the required region.

Sample Input

5
BLACK 1 1 2
BLACK 2 2 2
TEST 1 1 3
WHITE 2 1 1
TEST 1 1 3

Sample Output

7
6

Source

POJ Monthly--2004.05.15 Liu Rujia@POJ 

/* 二维树状数组,除了需要维护二维树状数组,还需要维护一个 当前各自颜色的数组 6121434 bobten2008 1656 Accepted 252K 16MS C++ 1382B 2009-11-13 13:17:49 树状数组和线段树是区间统计的利器,单词查询和插入的时间复杂度为O(lgn),具有较高的效率 */ #include <iostream> #include <cstring> #define MAX_N 105 using namespace std; int num[MAX_N + 1][MAX_N + 1]; int color[MAX_N + 1][MAX_N + 1]; int lowbit(int id) { return id & (id ^ (id - 1)); } void modify(int x, int y, int change) { int i, j; int val; if(color[x][y] == change) return; if(change == 1) val = 1; else if(color[x][y] == 1) val = -1; color[x][y] = change; if(val == 0) return; for(i = x; i <= MAX_N; i += lowbit(i)) for(j = y; j <= MAX_N; j += lowbit(j)) num[i][j] += val; } int sum(int x, int y) { int res = 0, i, j; for(i = x; i >= 1; i -= lowbit(i)) for(j = y; j >= 1; j -= lowbit(j)) res += num[i][j]; return res; } int main() { int cn; char command[10]; int x, y, L, i, r, c; scanf("%d", &cn); for(i = 1; i <= cn; i++) { scanf("%s%d%d%d", command, &x, &y, &L); if(strcmp(command, "WHITE") == 0) { for(r = x; r < x + L; r++) for(c = y; c < y + L; c++) modify(r, c, 0); } else if(strcmp(command, "BLACK") == 0) { for(r = x; r < x + L; r++) for(c = y; c < y + L; c++) modify(r, c, 1); } else { int count1 = sum(x + L - 1, y + L - 1); int count2 = sum(x + L - 1, y - 1); int count3 = sum(x - 1, y + L - 1); int count4 = sum(x - 1, y - 1); printf("%d/n", count1 - count2 - count3 + count4); } } return 0; } 

你可能感兴趣的:(command,Integer,input,each,output,Numbers)