hdu1556Color the ball(线段树)
2016-05-22 21:31
323 查看
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,因此有时需要离散化让空间压缩。
第一次接触线段树,题目很简单,如果按照一般思路时间复杂度是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; }
相关文章推荐
- HTML---网络编程基础知识(2)
- Spark多文件输出(MultipleOutputFormat)
- 问题 H: 不开心的小明③
- 【caffe-Windows】cifar实例编译之model的生成
- go语言的变量声明
- c++作业6
- GridView1 footer求和
- 复制、粘贴一个物体的所有组件
- HOOJ1290 2050(递推)
- 【IIS问题】——默认网站localhost无法打开,错误类型404
- C3P0数据源
- dnscrypt-proxy+dnsmasq搭建无污染DNS服务器
- sql 高级
- 语法分析(10)...
- 关于Maven+SpringMvc4.2版本返回json配置
- webView的用法总结。
- c++中的 template<class Type>
- HDU 5701 中位数计数 (暴力 思维题)
- android状态栏一体化(改变状态栏的背景颜色)
- 设计规划