hdoj1556-Color the ball

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

思路

 這題的解法可謂奇妙,首先我們用一個數組data來記錄信息,比如數據是a到b氣球塗色時,我們給data[a]加一,然後data[b+1]減一,然後當我們輸出結果時,聲明一個變量temp=0,然後在每次輸出第i個氣球的結果前都加上data[i],然後temp的值即爲結果;

code

#include <iostream>
#include <cstring>
#include <cstdio>
#include <fstream>
using namespace std;

const int MAX = 100000+5;
int data[MAX];

int main()
{
        int n;
        //freopen("data.in", "r", stdin);
        while(scanf("%d", &n) && n != 0)
        {
                memset(data, 0, sizeof(data));
                for(int i = 0; i < n; ++ i)
                {
                        int a, b;
                        scanf("%d%d", &a, &b);
                        data[a] ++;
                        data[b+1] --;
                }
                int temp = 0;
                for(int i = 1; i <= n; ++ i)
                {
                        temp += data[i];
                        if(i > 1)
                        {
                                printf(" ");
                        }
                        printf("%d", temp);
                }
                printf("\n");
        }
        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章