Created
May 29, 2017 22:00
-
-
Save KirillLykov/1be250c0be4fc927dfd418656617b657 to your computer and use it in GitHub Desktop.
kruscal implementation
This file contains hidden or 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 <cmath> | |
| #include <cstdio> | |
| #include <vector> | |
| #include <iostream> | |
| #include <algorithm> | |
| using namespace std; | |
| class disjoint_sets | |
| { | |
| vector<int> parent; | |
| vector<int> rank; | |
| public: | |
| disjoint_sets(size_t sz) : parent(sz, -1), rank(sz, -1) {} | |
| void make_set(int v) | |
| { | |
| parent[v] = v; | |
| rank[v] = 0; | |
| } | |
| int find_set(int x) | |
| { | |
| if (parent[x] != x) | |
| return parent[x] = find_set(parent[x]); | |
| return x; | |
| } | |
| void union_sets(int l, int r) | |
| { | |
| int pl = find_set(l); | |
| int pr = find_set(r); | |
| if (pl != pr) { | |
| if (rank[pl] < rank[pr]) | |
| swap(pl, pr); | |
| parent[pr] = pl; | |
| if (rank[pr] == rank[pl]) | |
| rank[pl] += 1; | |
| } | |
| } | |
| void print() | |
| { | |
| for_each(parent.begin(), parent.end(), [] (int v) { cout << v << ", ";}); | |
| cout << "\n"; | |
| } | |
| }; | |
| struct WEdge | |
| { | |
| int f, l, w; | |
| }; | |
| int main() { | |
| int n, m; | |
| cin >> n >> m; | |
| disjoint_sets ds(n); | |
| for (int i = 0; i < n; ++i) { | |
| ds.make_set(i); | |
| } | |
| vector<WEdge> edges(m); | |
| for (int i = 0; i < m; ++i) { | |
| cin >> edges[i].f >> edges[i].l >> edges[i].w; | |
| --(edges[i].f); --(edges[i].l); | |
| } | |
| sort(edges.begin(), edges.end(), [](const WEdge& le, const WEdge& re) | |
| { return le.w == re.w ? le.f + le.w + le.l < re.f + re.w + re.l : le.w < re.w;} ); | |
| int w = 0; | |
| for (auto e: edges) { | |
| if (ds.find_set(e.f) != ds.find_set(e.l)) { | |
| ds.union_sets(e.f, e.l); | |
| w += e.w; | |
| } | |
| } | |
| cout << w << "\n"; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment