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
- hdu1556Color the ball(线段树)
- hdu1556Color the ball线段树区间更新
- hdu1556Color the ball
- hdu1556Color the ball
- Color the ball (线段树)
- Color the ball(线段树)
- Color the ball(线段树)
- HDOJ Color the ball (线段树方法)
- hdu 1556 Color the ball(线段树+懒惰标记)
- hdu 1556 Color the ball(线段树)
- hdu 题目1556 Color the ball(线段树)
- 线段树--Color the ball(多次染色问题)
- ZOJ2301(HDU1199) Color the Ball(线段树离散化)
- hdu 1566 Color the ball(线段树区间更新)
- hdoj 1556 Color the ball(线段树||树状数组)
- HDU 1556 Color the ball(线段树)
- HDU 1556 Color the ball(线段树)
- HDOJ 1556 Color the ball(树状数组 & 线段树)
- c++作业6
- Android Notification的基本应用 (8.1)
- HTML---网络编程基础知识(2)
- Android高级UI SwipeRefreshLayout下拉刷新
- HDU 5583 Kingdom of Black and White [Ad Hoc]
- hdu1556Color the ball(线段树)
- go语言的变量声明
- 逻辑运算符与关系运算符
- hihoCoder 1287 Miller-Rabin质数测试
- 问题 F: 因子和
- 使用Android studio 开发xposed插件
- 一些其它
- C语言中的atan和atan2
- Java---基于TCP协议的相互即时通讯小程序