-
时间:2016-04-14 14:48:44 星期四
-
题目编号:[2016-04-14][POJ][1287][Networking]
-
题目大意:求最小生成树
-
分析:直接prim算法,更新边的时候,重边取最小值
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 50 + 10;
const int inf = 0x3f3f3f3f;
int g[maxn][maxn],vis[maxn],lowc[maxn];
int prim(int n){
int ans = 0;
memset(vis,0,sizeof(vis));
for(int i = 2 ; i <= n ; ++i) lowc[i] = g[1][i];
vis[1] = 1;
for(int i = 2 ; i <= n ;++i){
int minc = inf;
int p = -1;
for(int j = 1 ;j <= n ;++j){
if(!vis[j] && minc > lowc[j]){
minc = lowc[j];
p = j;
}
}
if(minc == inf) return -1;
ans += minc;
vis[p] = 1;
for(int j = 1 ; j <= n ; ++j){
if(!vis[j] && lowc[j] > g[p][j])
lowc[j] = g[p][j];
}
}
return ans;
}
int main(){
//freopen("in.txt","r",stdin);
int n,m;
while(~scanf("%d",&n) && n){
scanf("%d",&m);
int a,b,c;
memset(g,0x3f,sizeof(g));
for(int i = 1; i <= m ; ++i ){
scanf("%d%d%d",&a,&b,&c);
g[a][b] = min(c,g[a][b]);
g[b][a] = g[a][b];
}
printf("%d\n",prim(n));
}
return 0;
}
时间: 2024-10-12 17:04:32