優先順序隊列 (小根堆)

來源:互聯網
上載者:User

#include <iostream><br />#include <cstdlib><br />#include <ctime><br />using namespace std;<br />// 小根堆<br />template < typename T, int N = 10 ><br />class PriQueue<br />{<br />T * queue;<br />int cnt;<br />public:<br />PriQueue() : queue ( NULL ), cnt(0)<br />{<br />queue = new T[N]();<br />}<br />~PriQueue()<br />{<br />delete [] queue;<br />}<br />bool insert( T value)<br />{<br />if ( cnt >= N )<br />return false;<br />queue[cnt++] = value; //插入到最後<br />int child = cnt-1;<br />while ( child > 0 )<br />{<br />int parent = (child-1)/2;<br />if ( queue[parent] > value )<br />{<br />queue[child] = queue[parent];//向上篩<br />child = parent;<br />}<br />else<br />{<br />break;<br />}<br />}<br />queue[child] = value;<br />return true;<br />}<br />bool deleteMin()<br />{<br />if ( cnt < 1 )<br />return false;<br />cout<< queue[0] <<endl;<br />queue[0] = queue[--cnt];<br />int i = 0;<br />int tmp = queue[0];<br />while ( i < cnt/2 )<br />{<br />int smallChild = i*2 + 1;<br />if ( smallChild + 1 < cnt && queue[smallChild] > queue[smallChild+1] )<br />++smallChild;</p><p>if ( tmp > queue[smallChild] )<br />{<br />queue[i] = queue[smallChild];<br />i = smallChild;<br />}<br />else<br />break;<br />}<br />queue[i] = tmp;<br />return true;<br />}<br />};<br />int main()<br />{<br />srand(time(NULL));<br />PriQueue<int> queue;<br />while ( queue.insert(rand()%30) );<br />while ( queue.deleteMin() );<br />return 0;<br />}<br />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.