Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- struct Edge {
- size_t x_, y_, w_;
- bool operator<(const Edge& r) const {
- return w_ < r.w_;
- }
- };
- struct Host {
- size_t root_, size_;
- };
- class UF {
- public:
- UF(size_t n):
- hosts_(n) {
- for (size_t i = 0; i < n; i++) {
- hosts_[i].root_ = i;
- hosts_[i].size_ = 1;
- }
- }
- size_t find_root(size_t x) {
- if (hosts_[x].root_ == x)
- return x;
- hosts_[x].root_ = find_root(hosts_[x].root_);
- return hosts_[x].root_;
- }
- bool union_sets(size_t a, size_t b) {
- size_t root1 = find_root(a), root2 = find_root(b);
- if (root1 != root2) {
- if (hosts_[root1].size_ > hosts_[root2].size_) {
- hosts_[root2].root_ = root1;
- hosts_[root1].size_ += hosts_[root2].size_;
- }
- else {
- hosts_[root1].root_ = root2;
- hosts_[root2].size_ += hosts_[root1].size_;
- }
- return true;
- }
- return false;
- }
- private:
- std::vector<Host> hosts_;
- };
- int main() {
- size_t n, m, k;
- std::cin >> n >> m >> k;
- UF cities(n + 1);
- std::vector<Edge> roads(m);
- for (size_t i = 0; i < k; i++)
- cities.union_sets(i, n);
- for (size_t i = 0, j = 0; i < 2 * m; i++) {
- size_t x = 0, y = 0;
- std::cin >> x >> y;
- if (x < y) {
- std::cin >> roads[j].w_;
- roads[j].x_ = x;
- roads[j].y_ = y;
- j++;
- }
- else
- std::cin >> x;
- }
- size_t price = 0;
- std::sort(roads.begin(), roads.end());
- for (auto cur: roads) {
- if (cities.union_sets(cur.x_ - 1, cur.y_ - 1)) {
- price += cur.w_;
- }
- }
- std::cout << price;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement