照著以下資料初步學習了樹狀數組:
樹狀數組題目集.pdf http://download.csdn.net/detail/handong1587/5659973
http://dongxicheng.org/structure/binary_indexed_tree/
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees 講的很詳細!
裡面用到位元運算,感覺有點奇淫巧計的意思。理解了原始數組與樹狀數組的對應關係之後就比較簡單了,不過想做進一步的應用就得多多練習了。
下面代碼AC過了,不過很奇怪,編譯器選G++老是提示逾時,選C++就能AC,Memory:4204K,Time:1672MS。
#include <iostream>#include <cstring>using namespace std;int X, N, T;int matrix[1005][1005];void updateMatVal(int x, int y, int val){while (x <= N) {int tmpy = y;while (tmpy <= N) {matrix[x][tmpy] += val;tmpy += tmpy & (-tmpy);}x += x & (-x);}}void update2D(int x1, int y1, int x2, int y2){updateMatVal(x1, y1, 1);updateMatVal(x1, y2+1, -1);updateMatVal(x2+1, y1, -1);updateMatVal(x2+1, y2+1, 1);}int getMatSum(int x, int y){int sum = 0;while (x > 0) {int tmpy = y;while (tmpy > 0) {sum += matrix[x][tmpy];tmpy -= tmpy & (-tmpy);}x -= x & (-x);}return sum;}int main(){//freopen("POJ2155_Matrix.txt", "r", stdin);cin>>X;while (X--) {cin>>N>>T;memset(matrix, 0, sizeof(matrix));for (int j=0; j<T; j++) {char cmd;cin>>cmd;if (cmd == 'Q') {int x, y;cin>>x>>y;cout<<getMatSum(x, y)%2<<endl;}if (cmd == 'C') {int x1, y1, x2, y2;cin>>x1>>y1>>x2>>y2;update2D(x1, y1, x2, y2);}}if (X > 0)cout<<endl;}return 0;}