先决条件:有序集和 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)