toj 2196 優先隊列和堆的用法

來源:互聯網
上載者:User

標籤:

很簡單的優先隊列或者堆的使用。

 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 優先隊列和堆的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.