File size: 1,998 Bytes
c4b0eef |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <functional>
using namespace std;
int t, n;
vector<int> parent, sz;
vector < pair<double, double> > point;
class comparator
{
public:
bool operator()(pair<double, pair<int,int>> &x, pair<double, pair<int,int>> &y)
{
return x.first > y.first;
}
};
priority_queue <pair<double, pair<int, int>>, vector<pair<double, pair<int, int>>>, comparator> pq;
void initialize()
{
point.clear();
parent.clear();
sz.clear();
sz.resize(n, 1);
parent.resize(n);
for (int i = 0; i < n; i++)
parent[i] = i;
}
double dist(double a, double b, double c, double d)
{
return sqrt(((a - c)*(a - c)) + ((b - d)*(b - d)));
}
void makeGraph()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if(i != j)
{
pq.push({ dist(point[i].first, point[i].second, point[j].first, point[j].second), {i, j} });
}
}
}
}
int find(int x)
{
if (x == parent[x])
{
return parent[x];
}
else
{
return parent[x] = find(parent[x]);
}
}
bool merge(int x, int y)
{
int px = find(x);
int py = find(y);
if(px == py)
{
return false;
}
else
{
if(sz[px] < sz[py])
{
swap(px, py);
}
parent[py] = px;
sz[px] += sz[py];
return true;
}
}
double mst()
{
double how = 0;
int count = 0;
while (!pq.empty())
{
pair< double, pair<int, int> > top = pq.top();
pq.pop();
if(count < n - 1 && merge(top.second.first, top.second.second))
{
how += top.first;
count++;
}
}
return how;
}
int main()
{
bool ok = false;
cin >> t;
while (t--)
{
cin >> n;
initialize();
for (int i = 0; i < n; i++)
{
double x, y;
cin >> x >> y;
point.push_back({ x,y });
}
makeGraph();
if (!ok) ok = true;
else cout << endl;
printf("%.2f\n", mst());
}
} |