当前位置: 代码迷 >> 综合 >> POJ 1287 Networking(最小生成树)
  详细解决方案

POJ 1287 Networking(最小生成树)

热度:22   发布时间:2023-11-06 18:33:00.0

题意:

最小生成树裸题,直接模板。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAX 0x3f3f3f3f
#define mx 55
using namespace std;
int ma[mx][mx],vis[mx],cost,dis[mx];
int n,m;
void init(){memset(dis, 63, sizeof(dis));memset(vis, 0, sizeof(vis));memset(ma, 63, sizeof(ma));cost=0;
}
void prim(){for(int i = 1; i <= n; i++){dis[i] = ma[1][i];}dis[1] = 0;vis[1] = 1;for(int i = 1; i < n; i++){int te = MAX,k = 0;for(int j = 1; j<= n; j++){if(!vis[j]&&dis[j] < te){te = dis[j];k = j;}}cost += te;vis[k] = 1;for(int j = 1; j <= n; j++){if(!vis[j]&&ma[k][j] < dis[j])dis[j] = ma[k][j];}}}
int main(){while(scanf("%d",&n)&&n){init();scanf("%d",&m);int a,b,c;for(int i = 0; i <m; i++){scanf("%d%d%d",&a,&b,&c);ma[a][b] = ma[b][a] = min(ma[b][a], c);}prim();cout<<cost<<endl;}return 0;
}


  相关解决方案