码迷,mamicode.com
首页 > 编程语言 > 详细

POJ 2155 Matrix 二维树状数组

时间:2015-07-09 18:03:56      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:二维树状数组

http://blog.csdn.net/u013368721/article/details/32333865

二维树状数组,是一维的演变版,没什么太大改动

要注意的是,这里数组必须重新定义,不能是默认定义a[i][j]表示a[i][j]的值,否则二维树状数组只能做到单点修改,区间查询,但此题需要区间修改。

所以不妨换定义,定义a[i][j]表示 a[ i1 ] [ j1 ] ( i =< i1 <= n && j <= j1 <= n )所有值之和,那么修改时,只需将 a [ x1 ][ y1 ] += 1, a [ x1 ][ y2 + 1 ] -= 1; a [ x2 ][ y1 + 1] -= 1; a[ x2 + 1 ][ y2 + 1 ] +=1; 这个操作不是简单的 +1 -1,而是在二维树状数组上进行。

如此,查找时,只需查找 a[x][y] 即可,这也不是简单的查找a[x][y],而是在二维树状数组上进行。具体看代码。

二维线段树个人还不会,一会学学博主的。

My code (Java)

import java.util.*;


public class Main {
    public static void main(String[] agrs){
        Scanner input = new Scanner(System.in);

        int T = input.nextInt();
        int n, m;
        BIT bit;

        for(int kase = 1; kase <= T; kase++){
            if(kase > 1) System.out.println();

            n = input.nextInt(); m = input.nextInt();
            bit = new BIT(n);

            for(int i = 1; i <= m; i++){
                String s = input.next();

                if(s.charAt(0) == ‘C‘){
                    int x1, y1, x2, y2;
                    x1 = input.nextInt();
                    y1 = input.nextInt();
                    x2 = input.nextInt();
                    y2 = input.nextInt();

                    bit.update(x1 , y1, +1);
                    bit.update(x1, y2 + 1, -1);
                    bit.update(x2 + 1, y1, -1);
                    bit.update(x2 + 1, y2 + 1, +1);
                }
                else{
                    int x, y;
                    x = input.nextInt();
                    y = input.nextInt();

                    int ans = bit.query(x, y);
                    ans = (ans % 2 + 2) % 2;

                    System.out.println(ans);
                }
            }
        }

        input.close();
    }
}


class BIT{
    int[][] a;
    int n;

    public BIT(int n){
        this.n = n;
        a = new int[n + 10][n + 10];
    }

    public void update(int x,int y,int val){
        for(int i = x; i <= n; i += i&-i){
            for(int j = y; j <= n; j += j&-j){
                a[i][j] += val;
                a[i][j] = (a[i][j] % 2 + 2) % 2;
            }
        }
    }

    public int query(int x,int y){
        int ans = 0;
        for(int i = x; i > 0; i -= i&-i){
            for(int j = y; j > 0; j -= j&-j){
                ans = (ans + a[i][j]) % 2;
            }
        }
        return ans;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

POJ 2155 Matrix 二维树状数组

标签:二维树状数组

原文地址:http://blog.csdn.net/uestc_peterpan/article/details/46818991

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!