当前位置: 代码迷 >> 综合 >> POJ 2253 Frogger (最短距离,dijkstra,裸题)
  详细解决方案

POJ 2253 Frogger (最短距离,dijkstra,裸题)

热度:96   发布时间:2023-12-13 19:34:45.0

题目意思:
一只青蛙从1号石头跳到2号石头,不能直接跳过去,需要借助其他的石头来跳,
求从1号石头到2号石头所有路径中的最大跳跃距离的最小值。

本题要点:
1、单源最短路径,dijkstra算法,裸题。
2、题目的点事以 坐标的形式给出,求出每两点之间的额距离,然后用 dijkstra 算法求出,以1
点为起点,终点是 2 点的最短距离 d[2]。注意,这里的最短距离,指的是路径上最大跳跃距离的最小值,
只需在原来的dijkstra 算法的代码改改即可。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
const int MaxN = 210;
const int MaxM = 40010;
int n, tot;
int head[MaxN], ver[MaxM],  Next[MaxM];
double d[MaxN], edge[MaxM];
bool vis[MaxN];struct Point
{
    int x, y;
}points[MaxN];void add(int x, int y, double z)
{
    ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;
}void dijkstra()
{
    for(int i = 1; i <= n; ++i){
    d[i] = 0x3f3f3f3f;}memset(vis, false, sizeof(vis));	d[1] = 0;priority_queue<pair<double, int> > q;q.push(make_pair(0, 1));while(q.size()){
    int x = q.top().second;q.pop();vis[x] = true;for(int i = head[x]; i; i = Next[i]){
    int y = ver[i];double z = edge[i], maxEdge = max(d[x], z);if(d[y] > maxEdge){
    d[y] = maxEdge;q.push(make_pair(-d[y], y));}}}
}int main()
{
    int cnt = 0;while(scanf("%d", &n) != EOF && n){
    tot = 0;memset(head, 0, sizeof(head));memset(Next, 0, sizeof(Next));for(int i = 1; i <= n; ++i){
    scanf("%d%d", &points[i].x, &points[i].y);}double x1, y1, x2, y2, z;for(int i = 1; i <= n; ++i){
    for(int j = i + 1; j <= n; ++j){
    x1 = points[i].x, x2 = points[j].x, y1 = points[i].y, y2 = points[j].y;z = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));add(i, j, z);	add(j, i, z);}}dijkstra();printf("Scenario #%d\n", ++cnt);printf("Frog Distance = %.3f\n\n", d[2]);}return 0;
}/* 2 0 0 3 43 17 4 19 4 18 50 *//* Scenario #1 Frog Distance = 5.000Scenario #2 Frog Distance = 1.414*/