forked from hacktoberfest2k20/DataStructures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrims's Algorithm.cpp
129 lines (106 loc) · 2.4 KB
/
Prims's Algorithm.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
/*Given an undirected, connected and weighted graph G(V, E) with V number of vertices(which are numbered from 0 to V - 1)
and E number of edges.Find and print the Minimum Spanning Tree(MST) using Prim's algorithm.*/
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll max(ll a, ll b)
{
if (a < b)
return b;
return a;
}
ll min(ll a, ll b)
{
if (a < b)
return a;
return b;
}
#define here cout << "here\n"
#define pp pair<int, int>
#define vpp vector<pp>
#define vecto vector<ll>
#define ss second
#define ff first
#define pb push_back
#define mp make_pair
#define INF LONG_MAX
#define IOS \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0)
#define ull unsigned long long int
#define f(i, n) for (int i = 0; i < n; i++)
#define rep(i, a, b) for (int i = a; i < b; i++)
ll findMinInd(ll n, bool visited[], ll weight[])
{
ll mini = INT_MAX, index = -1;
for (int i = 0; i < n; i++)
{
// cout << weight[i] << " ";
if (mini > weight[i] && visited[i] == false)
{
mini = weight[i];
index = i;
}
}
return index;
}
void solve()
{
bool visited[100000];
ll parent[100000];
ll weight[100000];
memset(visited, false, sizeof(visited));
memset(parent, -1, sizeof(parent));
ll v, e;
cin >> v >> e;
ll **arr = new ll *[v];
for (int i = 0; i < v; i++)
{
arr[i] = new ll[v];
for (int j = 0; j < v; j++)
{
arr[i][j] = 0;
}
}
for (int i = 0; i < v; i++)
{
weight[i] = INT_MAX;
}
for (int i = 0; i < e; i++)
{
ll a, b, c;
cin >> a >> b >> c;
arr[a][b] = c;
arr[b][a] = c;
}
weight[0] = 0;
while (1)
{
ll index = findMinInd(v, visited, weight);
if (index == -1)
break;
visited[index] = true;
for (int i = 0; i < v; i++)
{
if (weight[i] > arr[index][i] && !visited[i] && arr[index][i] != 0)
{
parent[i] = index;
weight[i] = arr[index][i];
}
}
}
for (int i = 0; i < v; i++)
{
if (parent[i] == -1)
{
continue;
}
cout << min(i, parent[i]) << " " << max(i, parent[i]) << " " << weight[i] << "\n";
}
}
int main()
{
IOS;
solve();
}