POJ 1656 二維樹狀數組

來源:互聯網
上載者:User

題意:給定100*100的網格,每個格子可以塗上黑色或者白色(初始時全部樹白色),經過一系列操作後輸出任意一個正方形地區內的黑色格子數。

#include <iostream>using namespace std;int c[110][110];int a[110][110];const int n = 100;int lowbit ( int x ){return x & ( -x );}void modify ( int x, int y, int v ){for ( int i = x; i <= n; i += lowbit(i) ){for ( int j = y; j <= n; j += lowbit(j) )c[i][j] += v;}}void update ( int x, int y, int l, int mark ){int x1 = x, x2 = x + l - 1, y1 = y, y2 = y + l - 1;for ( int i = x1; i <= x2; ++i ){for ( int j = y1; j <= y2; ++j ){if ( a[i][j] != mark ){a[i][j] = mark;modify ( i, j, mark );}}}}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 getSum ( int x, int y, int l ){int x1 = x, y1 = y, x2 = x + l - 1, y2 = y + l - 1;return sum ( x2, y2 ) - sum ( x1-1, y2 ) - sum( x2 , y1 - 1 ) + sum ( x1 - 1, y1 - 1);}int main(){int t, x, y, l;char oper[10];memset(c,0,sizeof(c));memset(a,-1,sizeof(a));scanf("%d", &t );while ( t-- ){scanf("%s", oper );scanf("%d%d%d", &x, &y, &l );if ( strcmp(oper, "BLACK") == 0 )update ( x, y, l, 1 );else if ( strcmp(oper, "WHITE") == 0 )update ( x, y, l, -1 );elseprintf ( "%d\n", getSum ( x, y, l ) );}return 0;}

此題直接求解0MS

#include <iostream>using namespace std;int a[110][110];void update ( int x1, int y1, int x2, int y2, bool mark ){for ( int i = x1; i <= x2; ++i )for ( int j = y1; j <= y2; ++j )a[i][j] = mark;}int getSum ( int x1, int y1, int x2, int y2 ){int i, j, sum = 0;for ( i = x1; i <= x2; ++i )for ( j = y1; j <= y2; ++j )if ( a[i][j] )++sum;return sum;}int main(){int t, x, y, l;char oper[10];memset(a,0,sizeof(a));scanf("%d", &t );while ( t-- ){scanf("%s", oper );scanf("%d%d%d", &x, &y, &l );if ( strcmp(oper, "BLACK") == 0 )update ( x, y, x+l-1, y+l-1, 1 );else if ( strcmp(oper, "WHITE") == 0 )update ( x, y, x+l-1, y+l-1, 0 );elseprintf ( "%d\n", getSum ( x, y, x+l-1, y+l-1 ) );}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.