georgiy110802

Untitled

Jan 9th, 2022 (edited)
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<int> p, _size;
  6. int ans;
  7.  
  8. struct Edge {
  9.     int from, to, cost;
  10. };
  11.  
  12. int find(int v) {
  13.     if (p[v] == v)
  14.         return v;
  15.     return p[v] = find(p[v]);
  16. }
  17.  
  18. void union_s(int a, int b, int w) {
  19.     a = find(a);
  20.     b = find(b);
  21.     if (a != b) {
  22.         ans += w;
  23.         if (_size[a] < _size[b])
  24.             swap(a, b);
  25.         p[b] = a;
  26.         _size[a] += _size[b];
  27.     }
  28. }
  29.  
  30.  
  31. int main() {
  32.     int n, m;
  33.     cin >> n >> m;
  34.     vector<Edge> es;
  35.     _size.resize(n, 1);
  36.     p.resize(n);
  37.     for (int i = 0; i < n; i++)
  38.         p[i] = i;
  39.     for (int i = 0; i < m; i++) {
  40.         int from, to, cost;
  41.         cin >> from >> to >> cost;
  42.         from--, to--;
  43.         es.push_back({from, to, cost});
  44.     }
  45.  
  46.     sort(es.begin(), es.end(), [](const Edge left, const Edge right) {
  47.         return left.cost < right.cost;
  48.     });
  49.  
  50.     for (auto e : es)
  51.         union_s(e.from, e.to, e.cost);
  52.  
  53.     cout << ans;
  54. }
  55.  
  56.  
  57. #include <bits/stdc++.h>
  58.  
  59. using namespace std;
  60.  
  61. const double INF = 1000000000.0;
  62.  
  63. double len(double x1, double y1, double x2, double y2) {
  64.     return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  65. }
  66.  
  67. int main() {
  68.     int n;
  69.     cin >> n;
  70.     double ans = 0.0;
  71.     vector<double> x(n), y(n);
  72.     for (int i = 0; i < n; ++i) {
  73.         cin >> x[i] >> y[i];
  74.     }
  75.     vector<bool> used (n);
  76.     vector<double> min_e (n, INF);
  77.     vector<int> sel_e (n, -1);
  78.     min_e[0] = 0;
  79.     for (int i = 0; i < n; ++i) {
  80.         int v = -1;
  81.         for (int j = 0; j < n; ++j)
  82.             if (!used[j] && (v == -1 || min_e[v] - min_e[j] > 1e-9))
  83.                 v = j;
  84.         used[v] = true;
  85. //        cout << min_e[v] << ' ' << v << '\n';
  86.         if (sel_e[v] != -1)
  87.             ans += min_e[v];
  88.         for (int to = 0; to < n; ++to)
  89.             if (min_e[to] - len(x[v], y[v], x[to], y[to]) > 1e-9) {
  90.                 min_e[to] = len(x[v], y[v], x[to], y[to]);
  91.                 sel_e[to] = v;
  92.             }
  93.     }
  94.     cout << fixed << setprecision(5) << ans;
  95.     return 0;
  96. }
Add Comment
Please, Sign In to add comment