2

boost::fibonacci_heap ライブラリを使用して Fast Marching アルゴリズムを実装しており、ハンドルを使用して要素を操作し始めていました。

以下の基本的なコードを書きました。コンパイルはうまくいきますが、動作がわかりません。

最初に、プッシュされた各要素のハンドルを配列に格納します。次に、ヒープから最初の要素を取り出し、ヒープ サイズが減少したことを確認します。

しかし、そのハンドルを使用して、ポップアウトされた要素の値を更新しようとします。この操作は (驚くべきことに?) 機能し、更新された要素はヒープの一番上にあります。ただし、新しい要素を適切にプッシュしていないため、ヒープ サイズは同じままです。

では、ポップアウトされた要素が更新されてヒープに戻るとどうなるでしょうか? ヒープはまだ有効ですか?

# include <boost/heap/fibonacci_heap.hpp>
# include <iostream>

using namespace std;
using namespace boost::heap;

struct node
{
  int index;
  double time;

  node(const int& i, double t) : index(i), time(t) {}
};

struct compare_node
{
  bool operator()(const node& n1, const node& n2) const
  {
    return (n1.time > n2.time);
  }
};

int main()
{
  fibonacci_heap< node, compare<compare_node> > heap;
  typedef fibonacci_heap< node, compare<compare_node>  >::handle_type handle_t;
  handle_t tab_handle[10];
  int n;
  double tt[10];

  // assign a set of arbitrary numbers to initialise array tt:
  tt[0] = 5.3;
  tt[1] = 0.25;
  tt[2] = 3.6;
  tt[3] = 1.75;
  tt[4] = 9.1;
  tt[5] = 2.54;
  tt[6] = 3.8;
  tt[7] = 6.1;
  tt[8] = 1.23;
  tt[9] = 7.32;

  // push the values of tt into the heap, and keep track of the handle of each element in the heap:
    for (n=0; n<10; n++)
      {
        tab_handle[n] = heap.push(node(n, tt[n]));
      }


    // display first element in heap
    cout << "first element in heap is :" << heap.top().index << " " << heap.top().time << "\n";

    // check size of the heap
    cout << "size of heap is :" << heap.size() << "\n";

    // remove top element
    heap.pop();

    // check size of the heap
    cout << "size of heap after pop is :" << heap.size() << "\n";

    // display first element in heap
    cout << "first element in heap is now :" << heap.top().index << " " << heap.top().time << "\n";

    // access value of a given element by index:
    cout << "element index 2 has time :" << (*tab_handle[2]).time << "\n";

    // attempt to access the element with handle tab_handle[1]: this element was actually popped out of the heap previously. But I can access it:
    cout << "element index 1 has time :" << (*tab_handle[1]).time << "\n";

    // update the time of an element using its handle. This is quite standard.
    heap.update(tab_handle[2],node(2, tt[2]/10));

    // but now I can also update the element that was popped out of the heap:
    heap.update(tab_handle[1],node(1, tt[1]/10));

    // display first element in heap
    cout << "first element in heap is now :" << heap.top().index << " " << heap.top().time << "\n";

    // check size of the heap
    cout << "size of heap after pop is :" << heap.size() << "\n";

    return 0;

}

端末出力:

first element in heap is :1 0.25 
size of heap is :10 
size of heap after pop is :9 
first element in heap is now :8 1.23 
element index 2 has time :3.6 
element index 1 has time :0.25 
first element in heap is now :1 0.025
size of heap after pop is :9
4

1 に答える 1