【问题标题】:Binary search by a key containing two variables通过包含两个变量的键进行二分搜索
【发布时间】:2018-04-09 10:09:16
【问题描述】:

我有一个排序数组对 (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 最小。我觉得这可以通过二进制搜索来完成,但我不知道如何。任何相关的帮助或链接。

【问题讨论】:

  • 给定 (1,1),数组是 ((2,3), (3,2)) - 你需要哪一个?
  • @Arvo minimum x 在这种情况下
  • 你可能想要std::lower_bound()

标签: c++ algorithm binary-search


【解决方案1】:

由于您有条件c>a and 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2017-01-11
    • 2018-10-06
    相关资源
    最近更新 更多