poj 2155 樹狀數組

來源:互聯網
上載者:User

照著以下資料初步學習了樹狀數組:

樹狀數組題目集.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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.