思路:模拟几个数会发现让绝对值大的距离相匹配花费相对小,所以将所有钻石矿的绝对值和矿工的绝对值分别存入两个数组,排序,两者都按从小到大计算距离相加即可。
Code:
#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
typedef long long ll;
const int Max = 1e6 + 5;
ll xx[Max], yy[Max];
int main()
{
int t;cin >> t;
while (t--)
{
int n;cin >> n;
int o = 0, p = 0;
for (int i = 1;i <= 2 * n;i++)
{
int x, y;cin >> x >> y;
if (x == 0) yy[++o] = abs(y);
else xx[++p] = abs(x);
}
sort(xx + 1, xx + 1 + n);
sort(yy + 1, yy + 1 + n);
double ans = 0;
for (int i = 1;i <= n;i++)
{
ans += sqrt(double(xx[i]*xx[i] + yy[i]*yy[i]));
}
cout <<fixed<< setprecision(15)<<ans << endl;
}
}