-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim.cpp
More file actions
58 lines (45 loc) · 770 Bytes
/
Copy pathPrim.cpp
File metadata and controls
58 lines (45 loc) · 770 Bytes
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
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXV = 1005;
const int INF = 1e6;
int cost[MAXV][MAXV];
int minc[MAXV];
bool used[MAXV];
int n;
int prim()
{
fill(minc, minc + n, INF);
memset(used, 0, sizeof(used));
minc[0] = 0;
int res = 0;
while(true)
{
int v = -1;
for(int i = 0; i < n; i++)
{
if(!used[i] && (v == -1 || minc[i] < minc[v]))
v = i;
}
if(v == -1) break;
used[v] = true;
res += minc[v];
for(int i = 0; i < n; i++)
{
minc[i] = min(minc[i], cost[v][i]);
}
}
return res;
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
scanf("%d", &cost[i][j]);
printf("%d\n", prim());
return 0;
}