HDU 2642 二維樹狀數組問題

簡單:Stars

http://acm.hdu.edu.cn/showproblem.php?pid=2642

題目大概意思: 在某個位置可以是 B (明亮的星星) 或者是 D (昏暗的星星) 當 Q x1 x2 y1 y2 時候 求 在 x1 y1 到 x2 y2 中一共有多上個星星。


思路:用二維樹狀數組進行模擬 其算法的效率爲 log(n) java 代碼如下:

import java.util.Scanner;
/*
 * 此題用 二維線段樹求解
 */
public class HDU2642 {
	int c[][];
	static final int n = 1001;
	boolean vis[][];
	public HDU2642(){
		c = new int[n][n]; vis = new boolean[n][n];
	}
	private int lowbit(int n){
		return n&(-n);
	}
	// 修改 給 x1 , x2 位置 增加  data 後的修改
	public void modify(int x, int y, int data){
		for(int i =x ; i<=n; i += lowbit(i)){
			for(int j=y; j<=n; j+= lowbit(j)){
				c[i][j] += data;
			}
		}
	}
	// 得到從 (0,0) 到 (x,y) 矩陣的 和
	public int sum(int x,int y){
		int result = 0;
		for(int i=x; i>0; i -= lowbit(i)){
			for(int j=y; j>0; j -= lowbit(j)){
				result += c[i][j];
			}
		}
		return result;
	}
	// 得到 (x1,y1) 到 (x2, y2) 的 子矩陣的和
	public int getSubMaxtrix(int x1, int y1, int x2, int y2){
		// 讓 x2>x1 y2>y1;
		if( x2 < x1){int temp = x1; x1 = x2; x2 = temp;};
		if( y2 < y1){int temp = y1; y1 = y2; y2 = temp;};
		return sum(x2,y2) - sum(x1-1,y2) - sum(x2,y1-1) + sum(x1-1,y1-1);
	}
	public void solve(){
		int m ;
		Scanner sc = new Scanner(System.in);
		m = sc.nextInt();
		for(int i=0; i<m; i++){
			String executeChar ; int x, y;
			executeChar = sc.next();
			if(executeChar.equals("B")){// 如果是 Bright 
				x = sc.nextInt(); y = sc.nextInt();
				x++; y++;
				if( !vis[x][y]){
					vis[x][y] = true; modify(x, y, 1);
				}
			}
			else if(executeChar.equals("D")){
				x = sc.nextInt(); y = sc.nextInt();
				x++; y++;
				if(vis[x][y]){
					vis[x][y] = false; modify(x,y,-1);
				}
			}
			else if(executeChar.equals("Q")){
				int x1,x2,y1,y2;
				x1 = sc.nextInt(); x2 = sc.nextInt(); y1 = sc.nextInt(); y2 = sc.nextInt();
				x1++; y1++; x2++; y2++;
				System.out.println(getSubMaxtrix(x1, y1, x2, y2));
			}
		}
	}
	public static void main(String[] args) {
		new HDU2642().solve();
	}
}

樹狀數組的知識點:

定義 如下: 有數組 a[1........n] 有 c[] 有 c[n] = a[ n - 2^k+1] + ...............a[n]; k 爲 n 化爲 2進制後 0  的個數。是在網上學的 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章