HDU——1556 【差分陣列&&樹狀陣列】Color the ball
阿新 • • 發佈:2018-11-10
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
ac程式碼一(樹狀陣列):
#include<cstring> #include<cstdio> #define maxn 100010 int n,ans,a,b,bit[maxn]; inline int low_bit(int x){ return x&(-x); } void update(int x,int e) { while(x>0){ bit[x]+=e; x-=low_bit(x); } } int query(int x) { ans=0; while(x<=n){ ans+=bit[x]; x+=low_bit(x); } return ans; } void in_output() { memset(bit,0,sizeof(bit)); for(int i=1;i<=n;i++){ scanf("%d%d",&a,&b); update(b,1); update(a-1,-1); } for(int i=1;i<=n;i++) { printf("%d%c",query(i),i==n?'\n':' '); } } int main() { while(scanf("%d",&n)&&n) { in_output(); } return 0; }
ac程式碼二(差分陣列):
#include<stdio.h> #include<string.h> const int maxn=1e5+2; int s[maxn]; int main() { int i,n,a,b,k; while(scanf("%d",&n)&&n) { memset(s,0,sizeof(s)); k=0; for(i=0;i<n;i++) { scanf("%d%d",&a,&b); s[a]++; s[b+1]--; } // for(i=0;i<=n;i++) // printf("%d ",s[i]); // printf("\n"); for(int i=1;i<n;i++) { k+=s[i]; printf("%d ",k); } printf("%d\n",k+s[n]); } }