Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 6578 | Accepted: 4229 |
Description
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)
Input
Output
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; }