hdu1556Color the ball(线段树)

http://acm.hdu.edu.cn/showproblem.php?pid=1556
第一次接触线段树,题目很简单,如果按照一般思路时间复杂度是O(N),线段树的时间复杂度是O(logN)。只是空间复杂度要O(2N),应此要优化空间。

线段树是一种二叉搜索树,与区间树相似,它将一个区间划分成一些单元区间,每个单元区间对应线段树中的一个叶结点。
对于线段树中的每一个非叶子节点[a,b],它的左儿子表示的区间为[a,(a+b)/2],右儿子表示的区间为[(a+b)/2+1,b]。因此线段树是平衡二叉树,最后的子节点数目为N,即整个线段区间的长度。
使用线段树可以快速的查找某一个节点在若干条线段中出现的次数,时间复杂度为O(logN)。而未优化的空间复杂度为2N,因此有时需要离散化让空间压缩。

#include<iostream>
using namespace std;
struct Node{
    int l, r;
    int mid;
    int cnt;
}tree[100000 * 3];

void _build(int l, int r, int index){
    tree[index].l = l;
    tree[index].r = r;
    tree[index].mid = (l + r) / 2;
    tree[index].cnt = 0;
    if (l == r) return;

    _build(l, tree[index].mid, index * 2);
    _build(tree[index].mid + 1, r, index * 2 + 1);
}
void _count(int a, int b, int index){
    if (a == tree[index].l&&b == tree[index].r){
        tree[index].cnt++;
        return;
    }
    //
    if (a > tree[index].mid){
        _count(a, b, index * 2 + 1);
    }
    else if (b <= tree[index].mid){
        _count(a, b, index * 2);
    }
    //横跨
    else{
        _count(a, tree[index].mid, index * 2);
        _count(tree[index].mid + 1, b, index * 2 + 1);
    }
}
void getR(int index, int count){
    if (tree[index].l == tree[index].r){
        if (tree[index].l == 1){
            cout << count + tree[index].cnt;
        }
        else
        {
            cout << " " << count + tree[index].cnt;
        }
        return;
    }
    getR(index * 2, count+tree[index].cnt);
    getR(index * 2 + 1, count+tree[index].cnt);
}

int main(){
    int N;
    while (cin >> N){
        if (!N) break;
        int a, b;
        _build(1, N, 1);
        for (int i = 0; i<N; i++){
            cin >> a >> b;
            _count(a, b, 1);
        }
        getR(1, 0);
        cout << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值