UVa 1001 Say Cheese (Floyd)

题目链接:http://acm.hust.edu.cn/vjudge/problem/35891

大体题意:给出n个球形洞的坐标和半径,以及小老鼠A和B的坐标,问小老鼠A最快多长时间能到达B的位置。

思路:把老鼠看作是半径为0的洞,这样问题就转化成了给出n+2个洞,求某两洞之间的最短距离。可以考虑Floyd算法,在初始化时,若两洞连心线的距离小于等于其半径之和,则两洞距离为0,否则,距离为连心线与两半径之差。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const int maxn = 100+10;
const int INF = 1e7 + 10;

double dp[maxn][maxn];
int x[maxn], y[maxn], z[maxn], r[maxn];

int main()
{
    int n;
    int kase = 0;
    while (scanf("%d",&n) && n+1) {
        for (int i = 1; i <= n+2; i++)
           for (int j = 1; j <= n+2; j++)
              if (i == j) dp[i][j] = 0;
              else dp[i][j] = INF;
        for (int i = 1; i <= n; i++) scanf("%d%d%d%d",x+i,y+i,z+i,r+i);
        for (int i = n+1; i <= n+2; i++) {
            scanf("%d%d%d",x+i,y+i,z+i);
            r[i] = 0;
        }
        for (int i = 1; i <= n+2; i++)
          for (int j = i+1; j <= n+2; j++) {
              double dist = sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j]) + (z[i]-z[j])*(z[i]-z[j]));
              if (dist > r[i]+r[j]) {
                 dp[i][j] = dp[j][i] = dist - (double)(r[i]+r[j]);
              }
              else dp[i][j] = dp[j][i] = 0;
          }
        for (int k = 1; k <= n+2; k++)
          for (int i = 1; i <= n+2; i++)
            for (int j = 1; j <= n+2; j++)
              dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);
        printf("Cheese %d: Travel time = %.0lf sec\n",++kase,dp[n+1][n+2]*10.0);
    }
}


你可能感兴趣的:(UVa,图论)