-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathPrims.cpp
More file actions
71 lines (66 loc) · 1.52 KB
/
Copy pathPrims.cpp
File metadata and controls
71 lines (66 loc) · 1.52 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
#include<bits/stdc++.h>
using namespace std;
int getminVertex(vector<int> &weight,vector<bool> &visited,int n)
{
int mini = -1;
for(int i=0;i<n;i++)
{
if(!visited[i] && (mini == -1 || weight[i]<weight[mini]))
{
mini =i;
}
}
return mini;
}
void prims(vector<vector<int>> a,int n,int e)
{
vector<int> weight(n,INT_MAX);
vector<int> parent(n);
vector<bool> visited(n,false);
parent[0]=-1;
weight[0]=1;
for(int i=0;i<n-1;i++)
{
int minvertex =getminVertex(weight,visited,n);
visited[minvertex] =true;
// explore all the neighbours of the minimum vertex and update
// parent and weight array after that
for(int j=0;j<n;j++)
{
if(!visited[j] && a[minvertex][j]!=0 )
{
if(weight[j] > a[minvertex][j])
{
weight[j] = a[minvertex][j];
parent[j] =minvertex;
}
}
}
}
for(int i=1;i<n;i++)
{
if(parent[i]<i)
{
cout<<parent[i]<<" "<<i<<" "<<weight[i]<<endl;
}
else
{
cout<<i<<" "<<parent[i]<<" "<<weight[i]<<endl;
}
}
}
int main()
{
int n,e;
cin>>n>>e;
vector<vector<int>> mat(n,vector<int> (n));
int x,y,weight;
for(int i=0;i<e;i++)
{
cin>>x>>y>>weight;
mat[x][y]=weight;
mat[y][x]=weight;
}
prims(mat,n,e);
return 0;
}