forked from rohitthapliyal2000/Competitive-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskal's Algorithm.cpp
More file actions
63 lines (57 loc) · 1.05 KB
/
Kruskal's Algorithm.cpp
File metadata and controls
63 lines (57 loc) · 1.05 KB
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
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector < pair < int, pair <int, int> > > arr;
int brr[3001+1];
int root(int i)
{
if(brr[i] == -1)
return i;
return root(brr[i]);
}
void start()
{
for(int i = 0; i <= 3000; i++)
{
brr[i] = -1;
}
}
bool cycle(int u, int v)
{
if(root(u) == root(v))
{
return true;
}
int uset = root(u);
int vset = root(v);
brr[uset] = vset;
return false;
}
int main()
{
int nodes, edges, u, v, w;
cin >> nodes >> edges;
for(int i = 0; i < edges; i++)
{
cin >> u >> v >> w;
arr.push_back(make_pair(w,(make_pair(u,v))));
}
sort(arr.begin(), arr.end());
start();
int counter = 0, sum = 0;
for(int i = 0; i < edges; i++)
{
if(!cycle(arr[i].second.first, arr[i].second.second))
{
counter++;
sum += arr[i].first;
}
if(counter == nodes-1)
break;
}
cout << sum;
return 0;
}