-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrimsLazy.cpp
156 lines (122 loc) · 3.08 KB
/
PrimsLazy.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/*
@Chiranjeevi
Date: 09-Jul-17
*/
/*
Prim's Algorithm for finding MST
Running time O(ElogE)
Extra Space Complexity O(E)
Uses lazy version of selecting edges from priority queue
Eager version(not implemented here) uses O(E) extra space (other than for graph representation)
*/
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct node{
int src;
int dst;
float wgt;
node *next;
};
struct compare{
bool operator()(node *e1, node *e2){
if(e1->wgt > e2->wgt)
return true;
else
return false;
}
};
node *newNode(int a, int b, float wgt){
node *temp=new node;
temp->src=a;
temp->dst=b;
temp->wgt=wgt;
temp->next=NULL;
return temp;
}
void addUWEdge(vector<node *> &gph, int a, int b, float wgt){
node *ptr=gph[a];
if(ptr==NULL)
gph[a]=newNode(a, b, wgt);
else{
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newNode(a, b, wgt);
}
ptr=gph[b];
if(ptr==NULL)
gph[b]=newNode(b, a, wgt);
else{
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newNode(b, a, wgt);
}
}
void createUWGraph(vector<node *> &gph, int E){
int a, b;
float wgt;
for(int i=0; i<E; i++){
cin>>a>>b>>wgt;
addUWEdge(gph, a, b, wgt);
}
}
void printUWGraph(vector<node *> &gph){
int V=gph.size();
node *ptr;
for(int i=0; i<V; i++){
ptr=gph[i];
while(ptr!=NULL){
cout<<ptr->src<<"--"<<ptr->dst<<" "<<ptr->wgt<<endl;
ptr=ptr->next;
}
}
}
void visit(int vertex, vector<node *> &gph, priority_queue<node *, vector<node *>, compare> &pq, bool mark[]){
node *ptr=gph[vertex];
mark[vertex]=true;
while(ptr!=NULL){
if(!mark[ptr->dst])
pq.push(ptr);
ptr=ptr->next;
}
}
void primsMST(vector<node *> &gph, queue<node *> &mst, bool mark[]){
priority_queue<node *, vector<node *>, compare> pq;
node *ptr;
int count=1;
int V=gph.size();
visit(0, gph, pq, mark);
while(!pq.empty() and count<V){
ptr=pq.top();
pq.pop();
if(mark[ptr->src] and mark[ptr->dst])
continue;
else
mst.push(ptr);
if(!mark[ptr->src])
visit(ptr->src, gph, pq, mark);
else
visit(ptr->dst, gph, pq, mark);
count++;
}
}
void printMST(queue<node *> mst){
node *ptr;
while(!mst.empty()){
ptr=mst.front();
mst.pop();
cout<<ptr->src<<"--"<<ptr->dst<<" "<<ptr->wgt<<endl;
}
}
int main(){
int V, E;
cin>>V>>E;
vector<node *> gph(V, NULL);
queue<node *> mst;
bool mark[V]={false};
createUWGraph(gph, E);
printUWGraph(gph);
primsMST(gph, mst, mark);
printMST(mst);
}