#include<bits/stdc++.h>
#define N 2020
using namespace std;
struct str
{
int u, v, w;
};
vector<str>v;
int parent[N];
bool compare(str a, str b)
{
return a.w < b.w;
}
int finds(int x)
{
if(parent[x] < 0)
return x;
return parent[x] = finds(parent[x]);
}
int unions(int a, int b, int w)
{
int u = finds(a);
int v = finds(b);
if(u == v)
return 0;
else
{
if(parent[u] <= parent[v])
{
parent[u] += parent[v];
parent[v] = u;
}
else
{
parent[v] += parent[u];
parent[u] = v;
}
return w;
}
}
int mst(int node)
{
for(int i=1;i<=node;i++)
parent[i] = -1;
sort(v.begin(), v.end(), compare);
int mn = 0, cnt = 0;
for(int i=0; i<v.size(); i++)
{
int s = unions(v[i].u, v[i].v, v[i].w);
if(s > 0)
{
mn += s;
cnt++;
}
if(cnt == node - 1)
break;
}
return mn;
}
int main()
{
int node, edge, fnode, snode, weight;
cout << "Enter Node Number :: ";
cin >> node;
cout << "Enter Edge Number :: ";
cin >> edge;
cout << "Enter Edge :: " << "\n";
for(int i=1; i<= edge; i++)
{
cin >> fnode >> snode >> weight;
v.push_back({fnode, snode, weight});
}
cout << "\nMinimum Cost :: " << mst(node) << "\n";
return 0;
}
Comments
Post a Comment