问题描述
我有一系列不能重叠的时间间隔 (t_start,t_end),即:t_end(i) > t_start(i+1).我想做以下操作:
I have got a series of time intervals (t_start,t_end), that cannot overlap, i.e.: t_end(i) > t_start(i+1). I want to do the following operations:
1) 添加新的 (Union of) 区间 [ {(1,4),(8,10)} U (3,7) = {(1,7),(8,10)} ]
2) 取出区间 [ (1,7) - (3,5) = {(1,3),(5,7)}
3)检查一个点或一个区间是否与我的系列中的一个区间重叠(交集)
4) 在某个点 [ {(1,4),(7,8)}: 4 和 7 之间存在长度为 3 的非间隔"].
1) Add new (Union of) intervals [ {(1,4),(8,10)} U (3,7) = {(1,7),(8,10)} ]
2) Take intervals out [ (1,7) - (3,5) = {(1,3),(5,7)}
3) Checking whether a point or a interval overlaps with an interval in my series (intersection)
4) Finding the first "non-interval" of a minimum length after some point [ {(1,4),(7,8)}: there is a "non-interval" of length 3 between 4 and 7 ].
我想知道实现这一点的好方法,复杂度低(所有操作的 log n 都可以).
I want to know good ways of implementing this, with low complexities (log n for all operations would do it).
相关问题:快速时间间隔查找的数据结构
推荐答案
It sounds like you could just use a balanced binary tree of all the boundary times.
例如,将 {(1,4), (8,10), (12,15)} 表示为包含 1、4、8、10、12 和 15 的树.
For example, represent {(1,4), (8,10), (12,15)} as a tree containing 1, 4, 8, 10, 12, and 15.
Each node needs to say whether it's the start or end of an interval. So:
8 (start)
/
1 (start) 12 (start)
/
4 (end) 10 (end) 15 (end)
(Here all the "end" nodes ended up at the bottom by coincidence.)
那么我认为您可以在 O(log n) 时间内完成所有操作.添加间隔:
Then I think you can have all your operations in O(log n) time. To add an interval:
找到停止时间,用同样的方法找出是否需要添加,删除它,或者都不需要.
Find the stop time, using the same method to find out if you need to add it, remove it, or neither.
(免责声明:如果您使用 C++ 并进行显式内存管理,那么在执行此操作时您最终可能会释放超过 O(log n) 块的内存,但实际上释放节点所需的时间应该是我想是向添加它的人收费.)
在给定时间后找到至少给定大小的第一个间隙也可以在 O(log n) 中完成,如果您还为每个节点缓存另外两条信息:
In every node, the size of the largest gap that appears in that subtree.
这篇关于处理区间的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!