1556 Color the ball
阿新 • • 發佈:2020-08-19
資源限制
Time Limit: 9000/3000 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others)
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)。這是一道樹狀陣列-[區間更新 單點查詢]模板題,詳情點選這裡.
把區間[a, b]內的所有值全部加上k或者減去k,然後查詢某個點的值,這裡我們引入差分,利用差分建樹.
以下,A[i]代表原陣列,D[j]代表差分陣列,規定A[0] = 0;
則有 A[i] = Σij=1D[j]; (D[j] = A[j] - A[j-1]),即A[i]的值等於查分D[i]的字首和.
那麼要改變區間[a, b]內的值,只需更改D[a]和D[b+1]兩個值即可。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <string> 6 #include <cmath> 7 #include <algorithm> 8 #define INF 0x3f3f3f3f 9 #define zero 1e-7 10 11 using namespacestd; 12 typedef long long ll; 13 const ll mod=1000000007; 14 const ll max_n=1e5+5; 15 int c[max_n]; 16 int n; 17 18 int lowbit(int x) { 19 return x&(-x); 20 } 21 22 void update(int i, int k) { 23 while(i<=n) { 24 c[i]+=k; 25 i+=lowbit(i); 26 } 27 } 28 29 int getsum(int i) { 30 int res=0; 31 while(i>0) { 32 res+=c[i]; 33 i-=lowbit(i); 34 } 35 return res; 36 } 37 38 int main() { 39 while(cin>>n, n) { 40 memset(c, 0, sizeof(c)); 41 int a, b; 42 for(int i=1; i<=n; i++) { 43 scanf("%d %d", &a, &b); 44 update(a, 1); 45 update(b+1, -1); 46 } 47 for(int i=1; i<=n; i++) { 48 if(i==n) printf("%d\n", getsum(i)); 49 else printf("%d ", getsum(i)); 50 } 51 } 52 return 0; 53 }