-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.cpp
75 lines (71 loc) · 1.54 KB
/
1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <string.h>
#include "common.h"
#define MAX 55
#define INF 1000000000
int graph[MAX][MAX] ;
bool visited[MAX];
int prim(int n)
{
int lowCost[MAX] ;
for(int i = 1 ; i <= n ; ++i)
{
lowCost[i] = graph[1][i] ;
}
memset(visited,false,sizeof(visited)) ;
visited[1] = true ;
lowCost[0] = INF ;
int sum = 0 ;
for(int i = 1 ; i < n ; ++i)
{
int index = 0 ;
for(int j = 1 ; j <= n ; ++j)
{
if(!visited[j] && lowCost[index]>lowCost[j])
{
index = j ;
}
}
if(index == 0)
break ;
sum += lowCost[index] ;
visited[index] = true ;
for(int j = 1 ; j <= n ; ++j)
{
if(!visited[j] && lowCost[j]>graph[index][j])
{
lowCost[j] = graph[index][j] ;
}
}
}
return sum ;
}
int main()
{
testin("data.in");
int n , m ;
while(scanf("%d",&n) && n)
{
scanf("%d",&m);
for(int i = 0 ; i < MAX ; ++i)
{
graph[i][i] = INF ;
for(int j = 0 ; j < i ; ++j)
{
graph[i][j] = graph[j][i] = INF ;
}
}
for(int i = 0 ; i < m ; ++i)
{
int x, y , len ;
scanf("%d%d%d",&x,&y,&len);
if(graph[x][y]>len)
{
graph[x][y] = graph[y][x] = len ;
}
}
int sum = prim(n) ;
printf("%d\n",sum) ;
}
return 0 ;
}