2016-12-15 7 views
0

私は最小ヒープを持っています。私はO(n)時間内に、ただ一つのループを使用して言うことで、このヒープ内の2つの最小値を取得できますか最小ヒープ抽出2最小要素

priority_queue<double, vector<double>, greater<double>> min_heap; 
// push vector values to heap 
for (const auto& e : rand) 
    min_heap.push(e); 

よろしくお願いいたします。

+0

あなたはPRIORITY_QUEUEを使用する方法を知っていますか?さまざまな方法とその複雑さが何であるか知っていますか? –

+0

@MooingDuckそんなに正直ではありません。明示的にそれらを使用していない、今私は学ぶ必要があるようだ。 –

答えて

3

ヒープが形成されたら、O(logn)時間に実行できます。あなたは1つのポップと2つのクエリでそれを行うことができます。

int min1 = min_heap.top(); //get the minimum element 
min_heap.pop(); //pop the minimum element from the heap 
int min2 = min_heap.top(); //get the second minimum element(the new top) 
min_heap.push(min1); //push the old 'top' to restore the heap to its old state 

するのに役立ちます。この見れ:http://en.cppreference.com/w/cpp/container/priority_queue

関連する問題