hdu 1556 Color the ball(樹狀數組)

來源:互聯網
上載者:User

標籤:樹狀數組

轉載請註明出處:http://blog.csdn.net/u012860063

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1556


Problem DescriptionN個氣球排成一排,從左至右依次編號為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
31 12 23 331 11 21 30
 Sample Output
1 1 13 2 1

解題思路:

樹狀數組中的每個節點都代表了一段線段區間,每次更新的時候,根據樹狀數組的特性可以把b以前包含的所有區間都找出來,然後把b之前的區間全部加一次染色次數。然後,再把a之前的區間全部減一次染色次數,這樣就修改了樹狀數組中的[a,b]的區間染色次數,查詢每一個點總的染色次數的時候,就可以直接向上統計每個父節點的值,就是包含這個點的所有區間被染色次數,這就是樹狀數組中向下查詢,向上統計的典型應用

樹狀數組版:

#include <cstdio>  #include <cstring>  #define maxn 100047  int c[maxn]; int n,t;int Lowbit(int x)  // 2^k{return x&(-x);}void update(int i, int x)//i點增量為x{while(i > 0){c[i] += x;i -= Lowbit(i);}}int sum(int x)//區間求和 [1,x]{int sum=0;while(x <= n){sum+=c[x];x +=Lowbit(x);}return sum;}int main() { int i,j, x, y;     while(scanf("%d",&n) && n)     {         memset(c,0,sizeof(c));         for(i = 1; i <= n; i++)        {             scanf("%d%d",&x,&y);            update(y,1);//將y以下的區間+1update(x-1,-1);//將x以下的區間-1        }for(j = 1; j < n; j++){printf("%d ",sum(j));}printf("%d\n",sum(n));    }     return 0; } 


非樹狀數組版:(其實也是運用了樹狀數組版的思路)

#include <cstdio>#include <cstring>int main(){int n, i, j, a[100047], x, y;while(scanf("%d",&n) && n){memset(a,0,sizeof(a));for(i = 1; i <= n; i++){scanf("%d%d",&x,&y);a[x]++,a[y+1]--;}int sum = a[1];printf("%d",a[1]);for(i = 2; i <= n; i++){sum+=a[i];printf(" %d",sum);}printf("\n");}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.