-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprims.cpp
More file actions
73 lines (57 loc) · 1.87 KB
/
Copy pathprims.cpp
File metadata and controls
73 lines (57 loc) · 1.87 KB
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
// Prim's Minimum Spanning Tree (MST)
#include <bits/stdc++.h>
using namespace std;
#define V 6
#define INF 9999
int minKey(int key[], bool mstSet[]){
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
void printMST(int parent[], int graph[V][V], string path[]){
cout<<"Edge \t Path \t Weight\n";
int totalcost=0;
for (int i = 1; i < V; i++){
cout<< parent[i] <<" - "<< i <<" \t" << path[i] <<" \t" << graph[i][parent[i]] <<" \n";
totalcost += graph[i][parent[i]];
}
cout << " total cost "<< totalcost<< endl;
}
void primMST(int graph[V][V])
{
int parent[V]; // store constructed MST
string path[V]; // path to vertex
int key[V]; // Key values used to pick minimum weight edge in cut
bool mstSet[V]; // set of vertices included in MST
for (int i = 0; i < V; i++)
key[i] = INF, mstSet[i] = false; // Initialize all keys as INFINITE
// Always include first 1st vertex in MST.
// Make key 0 so that this vertex is picked as first vertex.
key[0] = 0;
parent[0] = -1; // First node is always root of MST
for (int count = 0; count < V - 1; count++){
int u = minKey(key, mstSet);
mstSet[u] = true; // visited
for (int v = 0; v < V; v++)
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]){ // go over not vidited vertices
parent[v] = u, key[v] = graph[u][v];
path[v] = path[u] + ' ' + to_string(u);
}
}
// print the constructed MST
printMST(parent, graph, path);
}
// Driver code
int main()
{
int graph[V][V] = { { INF, 1, 1, 5, INF, INF },
{ 1, INF, 1, INF, 1, 4 },
{ 1, 1, INF, 6, 2 , INF},
{ 5, INF, 6, INF, INF , 7 },
{ INF, 1, 2, INF , INF , 3 },
{ INF , 4, INF , 7, 3, INF} };
primMST(graph);
return 0;
}