-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprim.cpp
54 lines (50 loc) · 1.25 KB
/
prim.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
#include<iostream>
#include<vector>
using namespace std;
#define V 1000
bool createsMST(int u, int v, vector<bool> inMST) {
if (u == v)
return false;
if (inMST[u] == false && inMST[v] == false)
return false;
else if (inMST[u] == true && inMST[v] == true)
return false;
return true;
}
void printMinSpanningTree(int cost[][V]) {
vector<bool> inMST(V, false);
inMST[0] = true;
int a, b;
int edgeNo = 0, MSTcost = 0;
while (edgeNo < V - 1) {
int min = INT8_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (cost[i][j] < min) {
if (createsMST(i, j, inMST)) {
min = cost[i][j];
a = i;
b = j;
}
}
}
}
if (a != -1 && b != -1) {
MSTcost += min;
inMST[b] = inMST[a] = true;
}
}
cout << MSTcost << endl;
}
int main() {
int m, n, u, v, w;
//cin >> m >> n;
int cost[V][V];
for (int counter1 = 0; counter1 < m; counter1++)
{
cin >> u >> v >> w;
cost[u][v] = w;
}
printMinSpanningTree(cost);
return 0;
}