POJ 2155 二維樹狀數組

來源:互聯網
上載者:User

題意: 給出一個矩形的左上方和右下角(類似於矩陣), 被矩形框住的點需要改變它的值(0,1),給出一些操作,要求輸出某點的值。
本題是改變地區而求點。以二維樹狀數組來記錄某點的改變次數。先想想一維數組,例如 c[1], c[2] , c[3], c[4], c[5], ....c[10], 假設要改變c[3]-c[5]間的地區,只需要把c[3]改變一次(它後面的點全都隨之改變一次), 然後再將c[6]改變一次,這樣的話,c[6]及其後面的點改變了兩次,即相當於不變。

#include <iostream>using namespace std;int c[1010][1010], n;int lowbit ( int x ){return x & ( -x );}void modify ( int x, int y ){for ( int i = x; i <= n; i += lowbit(i) ){for ( int j = y; j <= n; j += lowbit(j) )c[i][j]++;}}void update ( int x1, int y1, int x2, int y2 ){modify ( x1, y1 );modify ( x2 + 1, y2 + 1 );modify ( x1, y2 + 1 );modify ( x2 + 1, y1 );}int sum ( int x, int y ){int total = 0;for ( int i = x; i > 0; i -= lowbit(i) ){for ( int j = y; j > 0; j -= lowbit(j) )total += c[i][j];}return total;}int main(){int t, q, x1, y1, x2, y2;char oper[5];scanf("%d",&t);while ( t-- ){scanf("%d%d",&n,&q);memset(c,0,sizeof(c));while ( q-- ){scanf("%s",oper);if ( oper[0] == 'C' ){scanf("%d%d%d%d",&x1,&y1,&x2,&y2);update ( x1, y1, x2, y2 );}if ( oper[0] == 'Q' ){scanf("%d%d",&x1,&y1);printf("%d\n", sum ( x1, y1 ) % 2 );}}putchar('\n');}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.