思路:模拟几个数会发现让绝对值大的距离相匹配花费相对小,所以将所有钻石矿的绝对值和矿工的绝对值分别存入两个数组,排序,两者都按从小到大计算距离相加即可。
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;
}
}
本文介绍了一种通过排序和匹配来最小化矿工与钻石矿之间距离总和的方法。该算法首先收集并排序所有矿的位置坐标,然后将矿工与钻石矿进行配对,以求得最小总距离。
1485

被折叠的 条评论
为什么被折叠?



