【问题标题】:Why two seemingly lower_bound() same method has different processing time为什么两个看似lower_bound() 相同的方法具有不同的处理时间
【发布时间】:2016-04-27 14:26:24
【问题描述】:

当我解决算法问题时,由于时间问题,我的解决方案无法通过。
但我意识到,通过的和我的唯一区别是

bag.lower_bound(jewerly[i].first) != bag.end() //passed

lower_bound(bag.begin(), bag.end(), jewerly[i].first) != bag.end() //failed

我已经用clock() 进行了检查,它显然比另一个慢。

这两个代码有什么区别?


#include <cstdio>
#include <set>
#include <algorithm>
using namespace std;

const int MAXN = 300100;

bool cmp(pair<int, int> a, pair<int, int> b)
{
    if(a.second != b.second)
        return a.second > b.second;
    return a.first < b.first;
}

pair<int, int> jewerly[MAXN];
multiset<int> bag;

int main()
{
    int N, K, M;
    scanf("%d%d", &N, &K);

    int w, p;
    for(int i = 0; i<N; i++)
    {
        scanf("%d%d", &w, &p);
        jewerly[i] = {w, p};
    }

    for(int i = 0; i<K; i++)
    {
        scanf("%d", &M);
        bag.insert(M);
    }

    sort(jewerly, jewerly+N, cmp);

    clock_t begin = clock();

    long long sum = 0;
    for(int i = 0; i<N; i++)    // #1
    {
        if( bag.empty() ) break;
        if( lower_bound(bag.begin(), bag.end(), jewerly[i].first) != bag.end())
        {
            sum += jewerly[i].second;
            bag.erase(bag.lower_bound(jewerly[i].first));
        }
    }

    /*
    for(int i = 0; i<N; i++)   //#2
    {
        if( bag.empty() ) break;
        if( bag.lower_bound(jewerly[i].first) != bag.end())
        {
            sum += jewerly[i].second;
            bag.erase(bag.lower_bound(jewerly[i].first));
        }
    }
    */

    clock_t end = clock();    
    printf("%lf\n", double(end-begin));
}



测试输入 10 8 1 65 5 23 1 30 9 40 3 50 2 90 5 30 5 30 7 80 2 99 10 15 12 5 3 5 2 2

【问题讨论】:

    标签: algorithm c++11 set multiset


    【解决方案1】:

    std::lower_bound 无法访问std::multiset 的内部结构。它不是 O(log N),因为 std::multiset 的迭代器不是随机访问的(而且你不可能在 Theta(N) 中更快地实现非随机访问迭代器)

    std::multiset::lower_bound 确实可以访问树的结构,并且可以很容易地实现复杂度 O(tree height),即 O(log N)

    【讨论】:

    • 从技术上讲,比较次数是O(log N),但不是迭代器增量。你可能是对的。
    • 哦,谢谢!所以它的实现方式不同!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多