-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prim.cpp
55 lines (46 loc) · 1.36 KB
/
Prim.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
struct edge
{
edge(int f, int t, int w)
{
from = f ;
to =t ;
weight = w ;
}
int from ,to,weight;
bool operator< (const edge & e) const
{
return weight > e.weight;
}
};
pair <int , vector<edge> > PRIM (vector <vector<edge>> adjList) // O (E logV)
{
int N = adjList.size() , cost = 0;
vector<int> visited (N , 0) ;
vector<int> visited2 (N , 0) ;
vector<edge> Graph ;
priority_queue <edge> queueEdges ; // 1) priority_queue to sort edges
// queueEdges.push(edge(-1,0,0)); //add base edge
for(int j = 0 ; j<adjList.size() ; ++j)
{
for(int i = j+1 ; i<adjList[j].size() ; ++i) //3) Iterate on adjacent edges & add new edges, using e.to as src
{
edge conectedEdge = adjList[j][i];
// cout<< conectedEdge.weight<<" ";
queueEdges.push(conectedEdge);
}
// cout<<endl;
}
cout<<"queueEdgesSize: "<< queueEdges.size()<<endl;
while(!queueEdges.empty())
{
edge newEdge = queueEdges.top();
queueEdges.pop();
if ( visited2[newEdge.from] > 1 || visited2[newEdge.to] > 1 ) continue ;
visited2[newEdge.from] ++ ;
visited2[newEdge.to] ++ ;
cost+= newEdge.weight;
Graph.push_back(newEdge);
if(Graph.size()==N-1) break ;
}
return make_pair(cost, Graph );
}