標籤:
很簡單的優先隊列或者堆的使用。
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 //greater對int來說表示值越小優先順序越高,也可以自己定義比較函數 6 priority_queue< int, vector<int>, greater<int> > q; 7 char op[2]; 8 9 int main ()10 {11 int n;12 while ( cin >> n, n )13 {14 while ( n-- )15 {16 cin >> op;17 if ( op[0] == ‘B‘ )18 {19 int tmp;20 cin >> tmp;21 q.push(tmp);22 }23 else if ( op[0] == ‘G‘ )24 {25 cout << q.top() << endl; 26 q.pop();27 }28 }29 while ( !q.empty() )30 {31 q.pop();32 }33 }34 return 0;35 }
然後是堆的:
1 //make_heap函數的用法類似下面兩個函數 2 #include <algorithm> 3 #include <iostream> 4 using namespace std; 5 6 const int N = 100000; 7 int heap[N]; 8 char op[2]; 9 int cnt;10 11 bool cmp( int a, int b )12 {13 return a > b;14 }15 16 int main ()17 {18 int n;19 while ( cin >> n, n )20 {21 cnt = 0;22 while ( n-- )23 {24 cin >> op;25 if ( op[0] == ‘B‘ )26 {27 int tmp;28 cin >> tmp;29 //push_heap30 //注意push的用法,要先手動加入heap再調用31 heap[cnt++] = tmp;32 push_heap( heap, heap + cnt, cmp );33 }34 else if ( op[0] == ‘G‘ )35 {36 //pop_heap37 //注意pop的用法,pop只是將堆頂的元素放到了heap最末尾的位置38 pop_heap( heap, heap + cnt, cmp );39 cnt--;40 cout << heap[cnt] << endl;41 }42 }43 }44 return 0;45 }
toj 2196 優先隊列和堆的用法