题目链接:
Codeforces #352 Div2 C Recycling Bottles
题意:
有两个人A(ax,ay)和B(bx,by)需要将n件垃圾捡回垃圾箱C(cx,cy).每个人每次只可以捡一件垃圾,允许一个人捡垃圾而另一个人在原地不动,问两人将这些垃圾捡回垃圾箱至少需要走的距离.
分析:
先记录每件垃圾到A/B和垃圾箱的距离之差a[i]和b[i],初始时将ans都加上每件垃圾到垃圾箱的距离z[i]*2.
只需要考虑A和B捡的第一件垃圾的位置,其余的行为均可以看做是从垃圾箱出发到达一个垃圾再返回.
假设A捡第i件垃圾,B捡第j件垃圾,显然ans = ans + a[i] + b[i] .
只需要知道a[i]和b[j]的最小值,而且还需要判断最小值时是不是同一件垃圾.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#include <iomanip>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 100010;
double ax, ay, bx, by, cx, cy;
double x[MAX_N], y[MAX_N], z[MAX_N];
int n;
inline double dis(double x1, double y1, double x2, double y2)
{
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
struct Node{
double len;
int id;
Node() {}
Node(double _len, int _id) : len(_len), id(_id) {
}
bool operator < (const Node& rhs) const {
if(len != rhs.len) return len < rhs.len;
else return id < rhs.id;
}
}a[MAX_N], b[MAX_N];
int main()
{
IOS;
freopen("C.in", "r", stdin);
while( cin >> ax >> ay >> bx >> by >> cx >> cy){
cin >> n;
double ans = 0, tmp1, tmp2;
for(int i = 0; i < n; i++){
cin >> x[i] >> y[i];
z[i] = dis(x[i], y[i], cx, cy);
ans += 2 * z[i];
a[i] = Node(dis(x[i], y[i], ax, ay) - z[i], i);
b[i] = Node(dis(x[i], y[i], bx, by) - z[i], i);
}
if(n == 1){
ans += min(a[0].len, b[0].len);
cout << fixed << setprecision(12) << ans << endl;
continue;
}
sort(a, a + n);
sort(b, b + n);
tmp1 = a[0].len;
tmp2 = b[0].len;
if(tmp1 < 0 && tmp2 < 0 && a[0].id == b[0].id){ //同一件垃圾并且两个人都是可以缩小ans的
double tmp3 = min(tmp1, tmp2); //只有一个行动的情况
tmp3 = min(tmp3, a[0].len + b[1].len); //A选公共"最优"垃圾,B另外找一个"次优"垃圾
tmp3 = min(tmp3, a[1].len + b[0].len); //B选公共"最优"垃圾,A另外找一个"次优"垃圾
ans += tmp3;
cout << fixed << setprecision(12) << ans << endl;
continue;
}
if(tmp1 <= 0 && tmp2 <= 0){
ans += tmp1 + tmp2;
}else {
ans += min(tmp1, tmp2);
}
cout << fixed << setprecision(12) << ans << endl;
}
return 0;
}