c++ - 通过包含两个变量的键进行二进制搜索

标签 c++ algorithm binary-search

我有一个已排序的对 (x,y) 数组,它们按 x 排序,对于相同的 x,它们按 y 排序。为了澄清,一个例子是 (2,3),(2,4),(3 ,2),(3,4),(3,5)。对于给定的对 (a,b),我想找到对 (c,d) 使得 c>a 和 d>b 使得 c 和 d 最小。我觉得这可以通过二进制搜索来完成,但我不知道如何。与此相关的任何帮助或链接。

最佳答案

因为您有条件 c>a 和 d>b,我们将首先搜索可接受的 c 值,然后搜索最小的 d

auto compare_first = [](std::pair<int, int> const & a, std::pair<int, int> const & b){
    return a.first < b.first;
};

auto compare_second = [](std::pair<int, int> const & a, std::pair<int, int> const & b){
    return a.second < b.second;
};

std::vector<std::pair<int, int>> values { {2,3}, {2,4}, {3,2}, {3,4}, {3,5} };

std::pair<int, int> value { 2, 3 };

auto it_c = std::upper_bound(values.begin(), values.end(), value, compare_first);
auto it = std::upper_bound(it_c, values.end(), value, compare_second);

Live on ideone

关于c++ - 通过包含两个变量的键进行二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49730447/

相关文章:

Java SE 7 Arrays.binarySearch()

c++ - 使用运算符重载的程序产生垃圾输出

c++ - 返回模板

c++ - 如何在 C++ 中找到任意方向的最小边界框

java - 如何为任何给定坐标找到正确的邻居?

algorithm - 运行时分析说明

java - 如何在 Entry 类上调用 binarySearch() ?

c++ - 智能感知 : expression must have integral or enum type

c++ - 异步分布式文件传输

python - 运行时错误 : maximum recursion depth exceeded in Python