Color the ball
Time Limit : 9000/3000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 25 Accepted Submission(s) : 15
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,輸入結束。
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
//思路:樹狀數組模闆+巧妙思路
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAX = 100100;
int n;
int a[MAX], c[MAX];
int lowbit(int x)
{
return x&(-x);
}
void add(int k, int x)
{
while (k <= n)
{
c[k] += x;
k += lowbit(k);
}
}
int sum(int x)
{
int sum = 0;
while (x > 0)
{
sum += c[x];
x -= lowbit(x);
}
return sum;
}
int main()
{
int i;
while (scanf("%d", &n), n)
{
int x, y;
memset(a, 0, sizeof(a));
memset(c, 0, sizeof(c));
for (i = 1; i <= n; i++)
{
scanf("%d%d", &x, &y);
add(x, 1);
add(y + 1, -1);
}
for (i = 1; i < n; i++)
{
printf("%d ", sum(i));
}
printf("%d\n", sum(n));
}
return 0;
}