## 7-6 公路村村通 （30 分)

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3

12

``````#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#define MAX 1010
using namespace std;
int a[1002][1002];//村庄和村庄之间路的钱
int vis[1002];//标记
int n,m;
int findmin()
{
int minV;
int mindist = MAX;
for(int V = 1; V <= n; V++)
if(vis[V]&& vis[V] < mindist)
{
mindist = vis[V];
minV = V;//和村1最便宜的村庄
}
if(mindist != MAX)
return minV;
else
return -1;
}
int prim(int x)
{
int V;
for(V = 1; V <= n; V++)
vis[V] = a[1][V];//第一个村庄到所有村庄的钱
int s = 0,Vcount = 0;
vis[1] = 0;
Vcount++;
while(1)
{
V = findmin();
if(V < 0)
break;
s += vis[V];
Vcount++;//联通数
vis[V] = 0;//标记这个村庄去过
for(int W = 1; W <= n; W++)
if(a[V][W] < MAX)//村庄之间可连
if(vis[W] && a[V][W] < vis[W])
vis[W] = a[V][W];
}
if(Vcount < n)
return -1;
return s;
}
int main(void)
{
int v1,v2,weight;
cin>>n>>m;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
a[i][j] = MAX;
while(m--)
{
scanf("%d%d%d",&v1,&v2,&weight);
a[v1][v2] = a[v2][v1] = weight;
}
int s = prim(1);
printf("%d",s);
return 0;
}

``````

0条评论