-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathminimum_spanning_tree.cpp
88 lines (78 loc) · 1.56 KB
/
minimum_spanning_tree.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
#include<bits/stdc++.h>
using namespace std;
using namespace chrono;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
class DSU{
vector<ll> par,rank;
public:
DSU(ll n)
{
par.resize(n+1,0);
rank.resize(n+1,1);
for(ll i=1;i<=n;i++) par[i]=i;
}
ll findPar(ll x)
{
if(x==par[x]) return x;
return par[x]=findPar(par[x]);
}
ll merge(ll a,ll b,ll w)
{
a=findPar(a);
b=findPar(b);
if(a==b) return 0;
ll x=(rank[a]*rank[b]*w);
if(rank[a]<=rank[b]) {
par[a]=b;
rank[b]+=rank[a];
}
else{
par[b]=a;
rank[a]+=rank[b];
}
return x;
}
};
struct Edge{
ll u,v,weight;
bool operator<(Edge const& other){
return weight > other.weight;
}
};
void solve() {
// cout << "Enter the number of edges : ";
ll n;
cin>>n;
vector<Edge> adj,res;
ll mx=INT_MIN,mn=INT_MAX;
for(ll i=0;i<n;i++)
{
// cout << "Enter the two nodes between which the edge shall be present along with the weight of the edge : ";
ll a,b,w;
cin>>a>>b>>w;
Edge e;
e.u=a;
e.v=b;
e.weight=w;
mx=max(mx,max(a,b));
mn=min(mn,min(a,b));
adj.push_back(e);
}
DSU dsu=DSU(mx);
sort(adj.begin(),adj.end());
//for(auto&x:adj) cout<<x.u<<" "<<x.v<<" "<<x.weight<<endl;
ll sum=0;
for(auto&e:adj){
ll s=dsu.merge(e.u,e.v,e.weight);
sum+=s;
// cout<<s<<endl;
}
cout<< "Weight of the minimum spanning tree is : "<<sum<<endl;
}
int main() {
fastio();
solve();
}