Last active
November 27, 2019 15:43
-
-
Save shiponcs/bb45acbc1fc155fba56f72d2bd06e15f to your computer and use it in GitHub Desktop.
MST with Kruskal
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
//author: Abdul Matin | |
void init(int nodes) | |
{ | |
for(int i = 1; i <= nodes; i++) link[i] = i, size[i] = 1; | |
} | |
int root(int x) | |
{ | |
if(x != link[x]) return (link[x] = root(link[x])); | |
return x; | |
} | |
bool same(int a, int b) | |
{ | |
return root(a) == root(b); | |
} | |
void unite(int a, int b) | |
{ | |
a = root(a); | |
b = root(b); | |
if(size[a] < size[b]) swap(a, b); | |
size[a] += size[b]; | |
link[b] = a; | |
} | |
bool cmp(tuple <int, int, int> a, tuple <int, int, int> b) | |
{ | |
return get<2>(a) > get<2>(b); | |
} | |
int kruskal(vector< tuple <int, int, int> > edges ,int src, int end, int edgeNumber, int nodes){ | |
sort(edges.begin(), edges.end(), cmp); | |
init(nodes); | |
int ans = INT_MAX; | |
for(auto x: edges){ | |
int a = get<0>(x); | |
int b = get<1>(x); | |
int weight = get<2>(x); | |
if(!same(a, b)) {unite(a, b); ans = min(ans, weight);} | |
if(same(src, end)) return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment