hdu1556Color the ball(线段树)

来源:互联网 发布:熟练使用办公软件 编辑:程序博客网 时间:2024/06/05 10:57

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;}
0 0
原创粉丝点击