|
버그 맞습니다.
multiset을 사용한 코드에서는 삽입전에 대소 비교 루틴을 넣었는데,
heap 버전에서는 그걸 빼먹었습니다.
고쳐서 다시 올립니다.
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
#include <algorithm>
#include <iterator>
//---------------------------------------------------------------------------
using namespace std;
#pragma argsused
int main(int argc, char* argv[])
{
const int heap_size = 10;
int input, heap[heap_size];
ostream_iterator<int> out(cout, " "); // 출력 반복자 정의
cout << "Enter 10 numbers: ";
// heap[0..9]까지 입력받음
for (int i = 0; i < heap_size; ++i) {
cin >> input;
heap[i] = input;
}
// heap[0..9]를 힙으로 만듦: O(N) 복잡도
make_heap(&heap[0], &heap[heap_size]);
#ifdef _DEBUG // 디버그 모드에서는 힙의 내용 출력
cout << "After make_heap : ";
copy(&heap[0], &heap[heap_size], out); cout.put('\n');
#endif
cout << "Enter more numbers. Press [Ctrl+Z] and Enter to quit.\n";
while (cin >> input) { // ctrl+z 로 입력 정지
if (input < heap[0]) {
pop_heap( &heap[0], &heap[heap_size]); // 힙에서 가장 큰 값을 pop: O(log N)
#ifdef _DEBUG
cout << "After pop_heap : ";
copy(&heap[0], &heap[heap_size], out); cout.put('\n');
#endif
heap[heap_size - 1] = input; // push할 원소를 마지막에 놓음
push_heap(&heap[0], &heap[heap_size]); // 힙에 push: O(log N)
#ifdef _DEBUG
cout << "After push_heap : ";
copy(&heap[0], &heap[heap_size], out); cout.put('\n');
#endif
}
}
// 힙 전용 정렬 알고리듬: sort보다 상수배 만큼 빠릅니다. 그러므로 O(N log N)
sort_heap(&heap[0], &heap[heap_size]);
cout << "After sort_heap : "; // 당연히 sort_heap 후에는 더이상 힙이 아닙니다.
copy(&heap[0], &heap[heap_size], out); cout.put('\n');
return 0 ;
}
//---------------------------------------------------------------------------
|