Color the ball
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17044 Accepted Submission(s): 8513
Problem Description
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,输入结束。
当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
树状数组入门,区间更新,单点查询
1 //2016.8.10 2 //树状数组,区间更新,单点查询 3 #include<iostream> 4 #include<cstdio> 5 #include<cstring> 6 7 using namespace std; 8 9 int arr[100005], n;//arr[i]表示i管辖的范围内数字之和 10 11 int lowbit(int x){return x&(-x);} 12 13 int add(int pos, int tt) 14 { 15 for(int i = pos; i <= n; i+=lowbit(i)) 16 arr[i] += tt; 17 return 0; 18 } 19 20 int query(int pos) 21 { 22 int sum = 0; 23 for(int i = pos; i > 0; i-=lowbit(i)) 24 sum+=arr[i]; 25 return sum; 26 } 27 28 int main() 29 { 30 int a, b; 31 while(cin>>n) 32 { 33 memset(arr, 0, sizeof(arr)); 34 for(int i = 0; i < n; i++) 35 { 36 scanf("%d%d", &a, &b); 37 add(a, 1); 38 add(b+1, -1); 39 } 40 for(int i = 1; i <= n; i++) 41 if(i == n) 42 cout<<query(i)<<endl; 43 else cout<<query(i)<<" "; 44 } 45 46 return 0; 47 }
1 // 2018-03-28 2 3 import java.util.*; 4 5 public class Main { 6 7 public static void main(String[] args) { 8 Scanner cin = new Scanner(System.in); 9 10 int n; 11 while(cin.hasNext()) { 12 n = cin.nextInt(); 13 if(n == 0)break; 14 BinaryIndexedTrees bit = new BinaryIndexedTrees(n); 15 int l, r; 16 for(int i = 0; i < n; i++) { 17 l = cin.nextInt(); 18 r = cin.nextInt(); 19 bit.updata(l, r, 1); 20 } 21 22 for(int i = 1; i <= n; i++) { 23 if(i == n)System.out.printf("%d ", bit.query(i)); 24 else System.out.printf("%d ", bit.query(i)); 25 } 26 } 27 } 28 } 29 30 class BinaryIndexedTrees { 31 /* 32 * 区间更新,单点查询 33 */ 34 int n; 35 int [] e; 36 37 BinaryIndexedTrees(int _n) { 38 this.n = _n; 39 e = new int[n+1]; 40 } 41 42 // x+lowbit(x)表示到达x的父节点 43 // x-lowbit(x)表示到达x点管辖区间的下个区间的管辖点 44 int lowbit(int x) { 45 return x&(-x); 46 } 47 48 void add(int pos, int val) { 49 for(int i = pos; i <= n; i+=lowbit(i)) 50 e[i] += val; 51 } 52 53 int query(int pos) { 54 int sum = 0; 55 for(int i = pos; i > 0; i-=lowbit(i)) 56 sum += e[i]; 57 return sum; 58 } 59 60 // 给[l, r]区间内的每个数加上val 61 void updata(int l, int r, int val) { 62 add(l, val); 63 add(r+1, -val); 64 65 } 66 }