题目考察的是迪杰斯特拉算法, 注意将起始点和终点也都看作是半径为零的洞,然后统一计算洞与洞之间的距离即可,注意,当距离计算出来为负值的时候要将距离设置为零,这是一个小坑,其他的具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
const int Inf = 0x3f3f3f3f;
class Hole{
public:
double x, y, z, r;
};
class Solve{
public:
int n;
vector<Hole> hole;
Hole start, end;
double area[110][110];
double length[110];
double square(double x){
return x*x;
}
double Length(int i,int j){
double L = sqrt(square(hole[i].x - hole[j].x) +
square(hole[i].y - hole[j].y) + square(hole[i].z - hole[j].z)) - hole[i].r - hole[j].r;
return L;
}
void Init(){
hole.clear();
for (int i = 0; i < n; i++){
Hole temp;
cin >> temp.x >> temp.y >> temp.z >> temp.r;
hole.push_back(temp);
}
cin >> start.x >> start.y >> start.z;
start.r = 0;
cin >> end.x >> end.y >> end.z;
end.r = 0;
hole.push_back(start);
hole.push_back(end);
for (int i = 0; i < 110; i++)
for (int j = 0; j < 110; j++) area[i][j] = Inf;
for (int i = 0; i < n + 1; i++){
for (int j = i + 1; j <= n + 1; j++){
area[j][i] = area[i][j] =max(0.0,Length(i, j));
}
}
}
double Dijkstra(){
for (int i = 0; i < 110; i++) length[i] = 1000000;
length[n] = 0;
int visit[110];
memset(visit, 0, sizeof(visit));
for (int i = 0; i <= n + 1; i++){
int ind;
double m = 1000000;
for (int j = 0; j <= n + 1; j++){
if (!visit[j] && length[j] < m){
m = length[j];
ind = j;
}
}
visit[ind] = 1;
for (int j = 0; j <= n + 1; j++){
if (area[ind][j]!=Inf)
length[j] = min(length[j], length[ind] + area[ind][j]);
}
}
return length[n + 1];
}
double Deal(){
Init();
return Dijkstra();
}
};
int main(){
Solve a;
int Case = 0;
while (cin >> a.n){
Case++;
if (a.n == -1) break;
double res = a.Deal();
res *= 10;
cout << "Cheese " << Case << ": " << "Travel time = " <<setprecision(0)<<fixed<< res << " sec" << endl;
}
return 0;
}