HDU 1556.Color the ball【線段樹】【4月28】

Color the ball

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15393    Accepted Submission(s): 7682


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>
using namespace std;
const int MAX = 100010;
struct ss
{
    int left, right, value, mark;
}segtree[MAX*4];
int N, a, b, first;
void build(int root, int l, int r)
{
    segtree[root].left = l;
    segtree[root].right = r;
    if(l == r)
    {
        segtree[root].value = 0;
        segtree[root].mark = 0;
        return;
    }
    build(root*2, l, (l+r)/2);
    build(root*2+1, (l+r)/2+1, r);
    segtree[root].value = 0;
    segtree[root].mark= 0;
}
void add(int root, int l, int r)
{
    if(segtree[root].left > r || segtree[root].right < l) return;
    if(l <= segtree[root].left && r >= segtree[root].right)
    {
        segtree[root].mark ++;
        return;
    }
    add(root*2, l, r);
    add(root*2+1, l, r);
}
void answer(int root, int l, int r)
{
    if(l == r)
    {
        if(first == 0) cout <<" ";
        else first = 0;
        cout << segtree[root].value + segtree[root].mark;
        return;
    }
    segtree[root*2].mark += segtree[root].mark;
    segtree[root*2+1].mark += segtree[root].mark;
    answer(root*2, l, (l+r)/2);
    answer(root*2+1, (l+r)/2+1, r);
}
int main()
{
    while(scanf("%d", &N) != EOF && N)
    {
        first = 1;
        build(1, 1, N);
        for(int i = 0;i < N; ++i)
        {
            scanf("%d %d", &a, &b);
            add(1, a, b);
        }
        answer(1, 1, N);
        cout << endl;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章