不能用STL里的priority_queue来优化,因为当更新dist的时候,系统不能维护最小堆的性质而报错。如果还不理解,自己实现最小堆就会明白了...~ #include<iostream> //POJ1251 #include<queue> #include<time.h> using namespace std ; const int N =30 ; const int Max=999999; int k[N]; int p[N]; bool f[N]; int Heap[N]; int arc[N][N]; int heap_size; int Length_heap; int n; void Min_Heapify(int i){ int l=i<<1,r=l+1,smallest; if(l<=heap_size&&k[Heap[l]]<k[Heap[i]]) smallest=l; else smallest=i; if(r<=heap_size&&k[Heap[r]]<k[Heap[smallest]]) smallest=r; if(smallest!=i){ Heap[i]^=Heap[smallest]^=Heap[i]^=Heap[smallest]; Min_Heapify(smallest); } } void Build_Min_Heap(){ for(int i=Length_heap>>1;i>=1;i--){ Min_Heapify(i); } } int Heap_Extract_Min(){ if(heap_size<1){ printf("heap underflow/n"); return -1; } int Min=Heap[1]; Heap[1]=Heap[heap_size]; heap_size--; Min_Heapify(1); return Min; } void Heap_Decrease_Key(int i,int key){ if(key>k[Heap[i]]){ printf("new key is larger than current key./n"); return ; } int p=i>>1; while(i>1&&k[Heap[p]]>k[Heap[i]]){ Heap[p]^=Heap[i]^=Heap[p]^=Heap[i]; i=i>>1; p=i>>1; } } int MST_Prim(int r){ int sum=0; int i; int p[N]; for(i=1;i<=n;i++){ k[i]=Max; p[i]=r; f[i]=true; } k[r]=0; for(i=1;i<=n;i++){ Heap[i]=i; } Build_Min_Heap(); while(heap_size){ int u=Heap_Extract_Min(); f[u]=false; sum+=arc[u][p[u]]; for(i=1;i<=n;i++){ int t=Heap[i]; if(f[t]&&arc[u][t]){ if(k[t]>arc[u][t]){ k[t]=arc[u][t]; Heap_Decrease_Key(i,k[t]); p[t]=u; } } } } return sum; } int main(){ priority_queue<int> q; char c,cc[2];int pnt,dist; int i,j; while(scanf("%d",&n),n){ for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ if(i==j) arc[i][i]=0; else arc[i][j]=arc[j][i]=Max; } } for(i=0;i<n-1;i++){ scanf("%s%d",&c,&pnt); for(j=0;j<pnt;j++){ scanf("%s%d",&cc,&dist); arc[c-'A'+1][cc[0]-'A'+1]=arc[cc[0]-'A'+1][c-'A'+1]=dist; } } heap_size=Length_heap=n; printf("%d/n",MST_Prim(1)); } return 0; }