先决条件:有序集和GNU C++ PBDS
给定有序集合集和键K ,任务是在C++中找到集合中元素K的上限和下限。如果该元素不存在或无法计算两个范围,则打印-1 。
Ordered set is a policy based data structure in g++ that keeps the unique elements in sorted order. It performs all the operations as performed by the set data structure in STL in log(n) complexity. Apart from that, it performs two additional operations also in log(n) complexity like:
1. order_of_key (K): Number of items strictly smaller than K.
2. find_by_order(K): Kth element in a set (counting from zero).
例子:
Input: set[] = {10, 20, 30, 40, 50, 60}, K = 30
Output:
Lower Bound of 30: 30
Upper Bound of 30: 40
Explanation:
The lower bound for element 30 is 30 located at position 2
The upper bound for element 30 is 40 located at position 3
Input: set[] = {10, 20, 30, 40, 50, 60}, K = 60
Output:
Lower Bound of 60: 5
Upper Bound of 60: -1
方法:
- upper_bound(): upper_bound(key)函数返回的元素正好大于传入参数中的key。
- lower_bound(): lower_bound(key)函数返回与参数中传递的key等效的元素。如果键不存在于有序集合中,则函数应返回大于参数的元素。
- 为了实现upper_bound和lower_bound函数,可使用order_of_key()函数找到元素的索引(如果存在于作为参数传递的有序集中)。
- 现在,可以通过简单比较存在于此索引处的元素来找到下限和上限。
下面是lower_bound()和upper_bound()的实现:
CPP
// C++ program to implement the
// lower_bound() and upper_bound()
// using Ordered Set
#include
#include
#include
using namespace __gnu_pbds;
using namespace std;
// Ordered Set Tree
typedef tree, rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
ordered_set set1;
// Function that returns the lower bound
// of the element
int lower_bound(int x)
{
// Finding the position of the element
int pos = set1.order_of_key(x);
// If the element is not present in the set
if (pos == set1.size())
{
return -1;
}
// Finding the element at the position
else
{
int element = *(set1.find_by_order(pos));
return element;
}
}
// Function that returns the upper bound
// of the element
int upper_bound(int x)
{
// Finding the position of the element
int pos = set1.order_of_key(x + 1);
// If the element is not present
if (pos == set1.size())
{
return -1;
}
// Finding the element at the position
else
{
int element = *(set1.find_by_order(pos));
return element;
}
}
// Function to print Upper
// and Lower bound of K
// in Ordered Set
void printBound(int K)
{
cout << "Lower Bound of " << K << ": " << lower_bound(K)
<< endl;
cout << "Upper Bound of " << K << ": " << upper_bound(K)
<< endl;
}
// Driver's Code
int main()
{
set1.insert(10);
set1.insert(20);
set1.insert(30);
set1.insert(40);
set1.insert(50);
int K = 30;
printBound(K);
K = 60;
printBound(K);
return 0;
}
Lower Bound of 30: 30
Upper Bound of 30: 40
Lower Bound of 60: -1
Upper Bound of 60: -1
时间复杂度: O(log N)