-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimsAlgoritm.cpp
More file actions
90 lines (75 loc) · 1.5 KB
/
PrimsAlgoritm.cpp
File metadata and controls
90 lines (75 loc) · 1.5 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<bits/stdc++.h>
#define size 100
using namespace std;
int adj[size][size];
int key[size];
int p[size];
bool color[size];
int WHITE = 0;
int BLACK = 1;
class Node
{
public:
int ver,weight;
Node(int vr,int c)
{
ver = vr;
weight = c;
}
};
bool operator<(Node u, Node v)
{
return u.weight > v.weight;
}
void Prims(int v,int u)
{
int c = 0;
for(int i=1; i<= v; i++)
{
key[i] = INT_MAX;
color[i] = WHITE;
}
key[u] = 0;
p[u] = NULL;
priority_queue<Node>q;
q.push(Node(u,0));
while(!q.empty())
{
Node t = q.top();
q.pop();
for(int i = 1; i <= v; i++)
{
if(adj[t.ver][i]!=0)
{
if(color[i]==WHITE && adj[t.ver][i]<key[i])
{
key[i] = adj[t.ver][i];
p[i] = t.ver;
q.push(Node(i,key[i]));
}
color[t.ver] = BLACK;
}
}
}
for(int i = 2;i <= v; i++)
{
cout<<p[i]<<" "<<i<<" "<<adj[i][p[i]]<<endl;
c = c + adj[i][p[i]];
}
cout<<"Minimum Cost = "<<c<<endl;
}
int main()
{
freopen("in.txt","r",stdin);
int vertex,edge;
cin>>vertex>>edge;
for(int i=1; i <= edge; i++)
{
int u,v,w;
cin>>u>>v>>w;
adj[u][v] = w;
adj[v][u] = w;
}
Prims(vertex,1);
return 0;
}