#include <stdio.h>
#define MAXINT 0x7fffffff
#define Max 1001
int Graph[Max][Max];
int Prim(int N);
void DFS(int N, int i, int *Visited);
int main(int argc, char const *argv[])
{
// freopen("test.txt", "r", stdin);
int N, M;
scanf("%d %d", &N, &M);
for (int i = 1; i <= N; i++){
for (int j = 1; j <= N; j++){
Graph[i][j] = Graph[j][i] = MAXINT;
}
}
for (int i = 1; i <= M; i++){
int c1, c2, budget;
scanf("%d %d %d", &c1, &c2, &budget);
Graph[c1][c2] = Graph[c2][c1] = budget;
}
for (int i = 1; i <= N; i++)
Visited[i] = 0;
DFS(N, 1, Visited);
int flag = 1;
int Visited[N+1];
for (int j = 1; j <= N; j++){
if (Visited[j] == 0)
flag = 0;
}
if (flag){
int ans = Prim(N);
printf("%d", ans);
}
else
printf("-1");
return 0;
}
void DFS(int N, int i, int *Visited)
{
Visited[i] = 1;
for (int j = 1; j <= N; j++){
if (Visited[j] == 0 && Graph[i][j] != MAXINT){
DFS(N, j, Visited);
}
}
}
int Prim(int N)
{
int MST[N+1], dist[N+1], count = 0, sum = 0;
for (int i = 0; i <= N; i++)
MST[i] = 0;
for (int i = 1; i <= N; i++)
dist[i] = Graph[1][i];
dist[1] = 0;
while(1){
int mindist = MAXINT, v = -1;
for (int i = 1; i <= N; i++){
if (MST[i] == 0 && dist[i] < mindist){
v = i;
mindist = dist[i];
}
}
if (v == -1)
break;
MST[v] = 1, dist[v] = 0;
sum += mindist, count++;
for (int i = 1; i <= N; i++){
if (MST[i] == 0 && Graph[v][i] < dist[i])
dist[i] = Graph[v][i];
}
}
if (count < N)
return -1;
else
return sum;
}
08-图7 公路村村通
最新推荐文章于 2024-11-02 18:15:46 发布