-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGraph - Prim.txt
56 lines (40 loc) · 1.08 KB
/
Graph - Prim.txt
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
//Greedy
// Prim deals with vertex as compared to Kruskal dealing with edges
// Can make graph global and avoid passing
const int MAX = 1e4 + 5;
bool marked[MAX];
int prim(int source, vector < pair < int,int > > graph) {
priority_queue < pair<int,int> , vector<pair<int,int>>, greater<pair<int,int>> > nodes;
nodes.push(make_pair(0, source));
int minCost = 0;
while(!nodes.empty()) {
// Selecting node with min weight
pair <int, int> minNode = nodes.front();
nodes.pop();
int cost = minNode.first;
int node = minNode.second;
//Check if cycle exists
if(marked[node])
continue;
minCost += cost;
marked[node] = true;
for(int i=0; i<graph[node].size();i++) {
int neighborPair = graph[node][i];
int neighbor = neighborPair.second;
if(!marked[neighbor]) {
nodes.push(neighborPair);
}
}
}
return minCost;
}
int main () {
cin>>nodes>>edges;
vector < pair < int,int > > graph[nodes+1];
for(i=0 to edges) {
cin>>x>>y>>weight;
graph[x].push_back(make_pair(weight, y));
graph[y].push_back(make_pair(weight, x));
}
int minimumCost = prim(1, graph);
}