C ++设置:计数元素小于值 [英] C++ set: counting elements less than a value

查看:88
本文介绍了C ++设置:计数元素小于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个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 sets 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆