Networking POJ1287 最小生成樹Prim(注意判斷重邊)
阿新 • • 發佈:2018-11-19
http://poj.org/problem?id=1287
#include<iostream> #include<math.h> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #define maxn 106 #define INF 1000000 using namespace std; int n,m; int graph[maxn][maxn]; int lowcost[maxn]; int visited[maxn]; void createGraph() { memset(graph,INF,sizeof(graph)); memset(lowcost, 0, sizeof(lowcost)); memset(visited, 0, sizeof(visited)); int u,v,w; for(int i=1;i<=m;i++){ cin>>u>>v>>w; if(graph[u][v]>w) { graph[u][v]=graph[v][u]=w; }//Prim 演算法需要進行判斷最小重邊 } } void prim() { int sum=0,cnt=0; visited[1]=1; for(int i=1;i<=n;i++){ lowcost[i]=graph[1][i]; } while(true) { int minn=lowcost[1]; int index=1; for(int j=2;j<=n;j++){ if(!visited[j]&&lowcost[j]<minn){ minn=lowcost[j]; index=j; } } if(index==1)break; sum+=minn; cnt++; visited[index]=1; for(int j=1;j<=n;j++){ if(!visited[j]&&lowcost[j]>graph[index][j]) { lowcost[j]=graph[index][j]; } } } if(cnt==n-1)cout<<sum<<endl; else cout<<"?"<<endl; } int main() { while(cin>>n>>m&&n) { createGraph(); prim(); } return 0; }