Raslboyy

1377

Nov 21st, 2019
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <algorithm>
  5. #include <string>
  6. #include <math.h>
  7. #include <climits>
  8.  
  9. //#include <chrono>
  10. //#include <fstream>
  11. //#include <bits/stdc++.h>
  12.  
  13. #define mp make_pair
  14. #define pb push_back
  15. #define eb emplace_back
  16. #define x first
  17. #define y second
  18. #define sz(x) (int)x.size()
  19. #define all(x) begin(x), end(x)
  20. #define rall(x) rbegin(x), rend(x)
  21. #define FOR(i,a,b) for (int i = (a); i < (b); i++)
  22. #define RFOR(i,b,a) for (int i = (b) - 1; i >= (a); i--)
  23.  
  24. using namespace std;
  25.  
  26. typedef unsigned long long ull;
  27. typedef long long ll;
  28. typedef long double ld;
  29. typedef pair<int, int> pi;
  30. typedef pair<ll, ll> pl;
  31. typedef vector<int> veci;
  32. typedef vector<bool> vecb;
  33. typedef vector<vector<int>> vvi;
  34. typedef vector<vector<bool>> vvb;
  35.  
  36. const int INF_I = 1e9;
  37. const ll INF_LL = 1e18;
  38.  
  39. struct edge {
  40.     int a;
  41.     int b;
  42.     int cost;
  43. };
  44.  
  45. veci p, sz;
  46. int res = 0;
  47.  
  48. int find_set(int v) {
  49.     return (v == p[v] ? v : p[v] = find_set(p[v]));
  50. }
  51.  
  52. void union_set(int a, int b, int w) {
  53.     a = find_set(a);
  54.     b = find_set(b);
  55.     if (a != b) {
  56.         if (sz[a] < sz[b])
  57.             swap(a, b);
  58.         p[b] = a;
  59.         sz[a] += sz[b];
  60.         res += w;
  61.     }
  62. }
  63.  
  64. int main() {
  65.     /*ifstream cin("in.txt");
  66.     ofstream cout("out.txt");
  67.     auto start_time = chrono::high_resolution_clock::now();*/
  68.  
  69.     ios::sync_with_stdio(false);
  70.     cin.tie(0);
  71.     cout.tie(0);
  72.  
  73.    
  74.     int n, m;
  75.     cin >> n >> m;
  76.     p.assign(n, 0);
  77.     sz.assign(n, 1);
  78.     sz.assign(n, 0);
  79.     FOR(i, 0, n)p[i] = i;
  80.     vector<edge> vec(m);
  81.     FOR(i, 0, m) {
  82.         cin >> vec[i].a >> vec[i].b >> vec[i].cost;
  83.         vec[i].a--, vec[i].b--;
  84.     }
  85.  
  86.     sort(all(vec), [](edge a, edge b) {
  87.         return a.cost < b.cost;
  88.     });
  89.  
  90.     for (edge e : vec)
  91.         union_set(e.a, e.b, e.cost);
  92.     cout << res << "\n";
  93.    
  94.     /*auto end_time = chrono::high_resolution_clock::now();
  95.     chrono::duration<double> duration = end_time - start_time;
  96.     cout << duration.count() << "\n";
  97.     cin.close();
  98.     cout.close();*/
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment