天天看點

HDU——1556 Color the ball(樹狀數組)區間更新,單點求值

N個氣球排成一排,從左到右依次編号為1,2,3....N.每次給定2個整數a b(a <= b),lele便為騎上他的“小飛鴿"牌電動車從氣球a開始到氣球b依次給每個氣球塗一次顔色。但是N次以後lele已經忘記了第I個氣球已經塗過幾次顔色了,你能幫他算出每個氣球被塗過幾次顔色嗎?

Input

每個測試執行個體第一行為一個整數N,(N <= 100000).接下來的N行,每行包括2個整數a b(1 <= a <= b <= N)。 

當N = 0,輸入結束。

Output

每個測試執行個體輸出一行,包括N個整數,第I個數代表第I個氣球總共被塗色的次數。

Sample Input

3
1 1
2 2
3 3
3
1 1
1 2
1 3
0
           

Sample Output

1 1 1
3 2 1
           

題意:中文題,比較好了解,不解釋。

題解:樹狀數組,區間更新,單點求值,典型題。模闆題!!!

C++:

#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1e+5+10;
int a[MAX];
int t;
int lowbit(int x){//模闆寫法
	return x&-x;
}
int query(int x){//查詢
	int sum=0;
	while(x){
		sum+=a[x];
		x-=lowbit(x);
	}
	return sum;
}
void add(int x,int v){
	while(x<=t){
		a[x]+=v;
		x+=lowbit(x);
	}
}
void update(int x,int y,int v){//更新
	add(x,v);
	add(y+1,-v);
}
int main(){
	while(cin >> t,t){
		memset(a,0,sizeof(a));
		int w=t;
		while(w--){
			int x,y;
			cin >>x >> y;
			update(x,y,1);
		}
		for (int i = 1; i <= t;i++){
			if(i!=t) cout << query(i) << " " ;
			else cout << query(i) << endl;
		}
	}
	return 0;
}
           

Java:

import java.util.*;
public class Main {
	static Scanner cin = new Scanner(System.in);
	static int n,m;
	static int [] a;
	static int lowbit(int x) {
		return x&(-x);
	}
	static int query(int x) {
		int sum=0;
		while(x!=0) {
			sum+=a[x];
			x-=lowbit(x);
		}
		return sum;
	}
	static void add(int x,int v) {
		while(x<=n) {
			a[x]+=v;
			x+=lowbit(x);
		}
	}
	static void update(int x,int y,int v) { // 區間更新,更新區間開頭和區間結尾後一個就可以。
		add(x,v);
		add(y+1,-v);
	}
	public static void main(String[] args){
		while(cin.hasNext()) {
			n = cin.nextInt();
			a = new int[n+2];
			if(n==0) break;
			for (int i = 1; i <= n;i++) {
				int x = cin.nextInt();
				int y = cin.nextInt();
				update(x,y,1);
			}
			for (int i = 1; i <= n;i++) {
				if(i!=1) System.out.print(" "+query(i));//單點求值
				else System.out.print(query(i));//單點求值
			}
			System.out.println();
		}
		
		
	}
}