C ++设置:计数元素小于值 [英] C++ set: counting elements less than a value
问题描述
假设我有一个STL 设置< INT>小号
和 INT X
,我怎么能算在元素的数s
的小于 X
?
Assuming a I have an STL set <int> s
and an int x
, how can I count the number of elements in s
that are less than x
?
我正在寻找一个 O(log n)的
(或类似的;任何的合理优于 O(N)
)的解决方案;
I'm seeking an O(log n)
(or similar; anything that's reasonably better than O(n)
) solution;
我已经知道了的std ::距离(s.begin(),s.lower_bound(X))
,但是这是为O(n )
,我相信,因为设置
是不是随机访问。
I already know about std::distance(s.begin(), s.lower_bound(x))
, but that's O(n)
, I believe, because set
s aren't random-access.
推荐答案
您需要的是一个订单统计树是什么。它实质上是一个支持额外操作的增加(二进制搜索)树等级(X)
它给你的元素个数与小于或等于密钥元素 X
。本章Cormen,Leiserson,维斯特,斯坦因14; 算法导论应该给你的算法背景。
What you need is an 'order-statistics tree'. It is essentially an augmented (binary search) tree that supports the additional operation rank(x)
which gives you the number of elements with less or equal key as element x
. Chapter 14 in Cormen, Leiserson, Rivest, Stein; "Introduction to Algorithms" should give you the algorithmic background.
也有在网络的一些执行情况。
There is also some implementation on the web.
这篇关于C ++设置:计数元素小于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!