MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / main

Function main

CPP/graph_tree/Prim-Algo.cpp:4–56  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2using namespace std;
3
4int main(){
5 int N=5,m=6;
6 vector<pair<int,int> > adj[N];
7
8
9 adj[0].push_back({1,2});
10 adj[0].push_back({3,6});
11 adj[1].push_back({0,2});
12 adj[1].push_back({2,3});
13 adj[1].push_back({3,8});
14 adj[1].push_back({4,5});
15 adj[2].push_back({1,3});
16 adj[2].push_back({4,7});
17 adj[3].push_back({0,6});
18 adj[3].push_back({1,8});
19 adj[4].push_back({1,5});
20 adj[4].push_back({2,7});
21
22 int parent[N];
23 int key[N];
24 bool mstSet[N];
25
26 for (int i = 0; i < N; i++)
27 key[i] = INT_MAX, mstSet[i] = false;
28 key[0] = 0;
29 parent[0] = -1;
30 int ansWeight = 0;
31 for (int count = 0; count < N - 1; count++)
32 {
33
34 int mini = INT_MAX, u;
35
36 for (int v = 0; v < N; v++)
37{
38 if (mstSet[v] == false && key[v] < mini)
39 mini = key[v], u = v;
40}
41 mstSet[u] = true;
42
43 for (auto it : adj[u]) {
44 int v = it.first;
45 int weight = it.second;
46 if (mstSet[v] == false && weight < key[v])
47 parent[v] = u, key[v] = weight;
48 }
49
50 }
51
52
53 for (int i = 1; i < N; i++)
54 cout << parent[i] << " - " << i <<" \n";
55 return 0;
56}
57
58/*
59Output:

Callers

nothing calls this directly

Calls 1

push_backMethod · 0.80

Tested by

no test coverage detected