fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. #define int double
  5. #define endl "\n"
  6.  
  7. struct Edge {
  8. int u, v;
  9. double weight;
  10. bool operator<(const Edge &other) const {
  11. return weight < other.weight;
  12. }
  13. };
  14.  
  15. double dis(pair<double,double> a, pair<double,double> b){
  16. return sqrt(pow(a.first - b.first, 2) + pow(a.second - b.second, 2));
  17. }
  18.  
  19. int find(int x, vector<int> par){
  20. if(par[x] == x)return x;
  21. return find(par[x], par);
  22. }
  23.  
  24. bool join(int x, int y, vector<int> par){
  25. int u = find(x, par), v = find(y, par);
  26. if(u == v)return false;
  27. return true;
  28. }
  29.  
  30. double kruska(int n, vector<pair<double,double>> &points){
  31. vector<Edge> edges;
  32. vector<int> par(n + 1);
  33.  
  34. for(int i = 0; i < n; i++){
  35. par[i] = i;
  36. for(int j = i + 1; j < n; j++){
  37. edges.push_back({i,j,dis(points[i], points[j])});
  38. }
  39. }
  40.  
  41. sort(edges.begin(), edges.end());
  42.  
  43. int cnt = 0;
  44. double sum = 0.00;
  45.  
  46. for(int i = 0; i < edges.size(); i++){
  47. if(join(edges[i].u, edges[i].v,par)){
  48. par[edges[i].v] = edges[i].u;
  49. sum += edges[i].weight;
  50. cnt++;
  51. if(cnt == n - 1)break;
  52. }
  53. }
  54. return sum;
  55. }
  56.  
  57. signed main(){
  58. ios_base::sync_with_stdio(0);
  59. cin.tie(0);cout.tie(0);
  60. int tc;cin >> tc;
  61. string s; getline(cin, s);
  62. while(tc--){
  63. int n; cin >> n;
  64. vector<pair<double,double>> points(n);
  65.  
  66. for(int i = 0; i < n; i++){
  67. cin >> points[i].first >> points[i].second;
  68. }
  69.  
  70. double result = kruska(n ,points);
  71. cout << fixed << setprecision(2) << result << endl << endl;
  72. }
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.01s 5288KB
stdin
3

5
1.0 1.0
3.0 1.0
1.0 3.0
5.0 4.0
7.0 7.0

4
1.0 1.0
-1.0 1.0
-1.0 -1.0
1.0 -1.0

6
3.0 3.0
5.0 -2.0
8.0 4.0
12.5 -3.0
-5.0 -1.0
0.0 0.0
stdout
11.21

6.00

25.21