here I will try to implement the algorithm in my way
a normal undirected graph
After kruskal (MST):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
int rep[100005]; | |
struct edge{ | |
int a, b , c; | |
}arr[100005]; | |
bool cmp( edge x, edge y ){ | |
return x.c < y.c; | |
} | |
void makeset(int n){ | |
for(int i=1;i<=n;i++) rep[i]=i; | |
} | |
int findr( int x ){ | |
if( rep[x] == x ) return x; | |
return rep[x] = findr( rep[x] ); | |
} | |
int unio(int i,int sum){ | |
int x,y; | |
x = findr( arr[i].a ); | |
y = findr( arr[i].b ); | |
if( x != y ){ | |
rep[x] = y; | |
cout<<arr[i].a<<" "<<arr[i].b<<"\n";//connected edges | |
sum += arr[i].c; | |
} | |
return sum; | |
} | |
int main() | |
{ | |
int n , m; | |
cin >> n >> m; | |
makeset(n); | |
for( int i = 0; i < m; i++ ){ | |
int a, b, c ; | |
cin >> a >> b >> c; | |
arr[i].a = a; | |
arr[i].b = b; | |
arr[i].c = c; | |
} | |
sort( arr, arr+m , cmp ); | |
int sum=0; | |
for(int i=0;i<m;i++){ | |
sum=unio(i,sum); | |
} | |
cout << sum << "\n"; //cost | |
} |
No comments:
Post a Comment