-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathgraph_3.cpp
107 lines (88 loc) · 2.06 KB
/
graph_3.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <bits/stdc++.h>
using namespace std;
//Prims algorithm
//this is also a algorithm used to find the mst of a given graph
int findMinVertex(int* weights,bool* visited,int n){
int minVertex=-1;
for(int i=0;i<n;i++){
if(!visited[i] && (minVertex == -1 || weights[i]<weights[minVertex])){
minVertex=i;
}
}
return minVertex;
}
void prims(int** edges,int n){
int* parent = new int[n];
int* weights = new int[n];
bool* visited = new bool[n];
for(int i=0;i<n;i++){
visited[i]=false;
weights[i]=INT_MAX;
}
parent[0]=-1;
weights[0]=0;
for(int i=0;i<n;i++){
//find min vertex
int minVertex=findMinVertex(weights,visited,n);
visited[minVertex]=true;
//explore unvisited neighbour
for(int j=0;j<n;j++){
if(edges[minVertex][j]!=0 && !visited[j]){
if(edges[minVertex][j]<weights[j]){
weights[j]=edges[minVertex][j];
parent[j]=minVertex;
}
}
}
}
//printing the mst
for(int i=1;i<n;i++){
if(parent[i]<i){
cout<<parent[i]<<" "<<i<<" "<<weights[i]<<endl;
}else{
cout<<i<<" "<<parent[i]<<" "<<weights[i]<<endl;
}
}
}
int main() {
// Write C++ code here
cout<<"---------program started---------"<<endl;
int n;
int e;
cin>>n>>e;
int** edges = new int*[n];
for(int i=0;i<n;i++){
edges[i]=new int[n];
for(int j=0;j<n;j++){
edges[i][j]=0;
}
}
for(int i=0;i<e;i++){
int f,s,weight;
cin>>f>>s>>weight;
edges[f][s]=weight;
edges[s][f]=weight;
}
cout<<endl;
prims(edges,n);
for(int i=0;i<n;i++){
delete [] edges[i];
}
delete [] edges;
return 0;
}
/*input
5 7 (5 vertices and 7 edges)
0 1 4
0 2 8
1 3 6
1 2 2
2 3 3
2 4 9
3 4 5
output
0 1 4
1 2 2
2 3 3
3 4 5
*/