#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 />