Advertisement
Guest User

Untitled

a guest
May 3rd, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. struct Edge {
  4.     size_t x_, y_, w_;
  5.  
  6.     bool operator<(const Edge& r) const {
  7.         return w_ < r.w_;
  8.     }
  9. };
  10.  
  11. struct Host {
  12.     size_t root_, size_;
  13. };
  14.  
  15. class UF {
  16.  public:
  17.     UF(size_t n):
  18.         hosts_(n) {
  19.         for (size_t i = 0; i < n; i++) {
  20.             hosts_[i].root_ = i;
  21.             hosts_[i].size_ = 1;
  22.         }
  23.     }
  24.  
  25.     size_t find_root(size_t x) {
  26.         if (hosts_[x].root_ == x)
  27.             return x;
  28.         hosts_[x].root_ = find_root(hosts_[x].root_);
  29.         return hosts_[x].root_;
  30.     }
  31.  
  32.     bool union_sets(size_t a, size_t b) {
  33.         size_t root1 = find_root(a), root2 = find_root(b);
  34.         if (root1 != root2) {
  35.             if (hosts_[root1].size_ > hosts_[root2].size_) {
  36.                 hosts_[root2].root_ = root1;
  37.                 hosts_[root1].size_ += hosts_[root2].size_;
  38.             }
  39.             else {
  40.                 hosts_[root1].root_ = root2;
  41.                 hosts_[root2].size_ += hosts_[root1].size_;
  42.             }
  43.             return true;
  44.         }
  45.         return false;
  46.     }
  47.  private:
  48.     std::vector<Host> hosts_;
  49. };
  50.  
  51. int main() {
  52.     size_t n, m, k;
  53.     std::cin >> n >> m >> k;
  54.  
  55.     UF cities(n + 1);
  56.     std::vector<Edge> roads(m);
  57.     for (size_t i = 0; i < k; i++)
  58.         cities.union_sets(i, n);
  59.    
  60.     for (size_t i = 0, j = 0; i < 2 * m; i++) {
  61.         size_t x = 0, y = 0;
  62.         std::cin >> x >> y;
  63.         if (x < y) {
  64.             std::cin >> roads[j].w_;
  65.             roads[j].x_ = x;
  66.             roads[j].y_ = y;
  67.             j++;
  68.         }
  69.         else
  70.             std::cin >> x;
  71.     }
  72.  
  73.     size_t price = 0;
  74.     std::sort(roads.begin(), roads.end());
  75.  
  76.     for (auto cur: roads) {
  77.         if (cities.union_sets(cur.x_ - 1, cur.y_ - 1)) {
  78.             price += cur.w_;
  79.         }
  80.     }
  81.  
  82.     std::cout << price;
  83.  
  84.     return 0;
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement