C++图论提高例题讲解————Frogger

题目描述:

Freddy Frog is sitting on a stone in the middle of a lake. Suddenly he notices Fiona Frog who is sitting on another stone. He plans to visit her, but since the water is dirty and full of tourists' sunscreen, he wants to avoid swimming and instead reach her by jumping. 
Unfortunately Fiona's stone is out of his jump range. Therefore Freddy considers to use other stones as intermediate stops and reach her by a sequence of several small jumps. 
To execute a given sequence of jumps, a frog's jump range obviously must be at least as long as the longest jump occuring in the sequence. 
The frog distance (humans also call it minimax distance) between two stones therefore is defined as the minimum necessary jump range over all possible paths between the two stones. 

You are given the coordinates of Freddy's stone, Fiona's stone and all other stones in the lake. Your job is to compute the frog distance between Freddy's and Fiona's stone. 

输入:

The input will contain one or more test cases. The first line of each test case will contain the number of stones n (2<=n<=200). The next n lines each contain two integers xi,yi (0 <= xi,yi <= 1000) representing the coordinates of stone #i. Stone #1 is Freddy's stone, stone #2 is Fiona's stone, the other n-2 stones are unoccupied. There's a blank line following each test case. Input is terminated by a value of zero (0) for n.

输出:

For each test case, print a line saying "Scenario #x" and a line saying "Frog Distance = y" where x is replaced by the test case number (they are numbered from 1) and y is replaced by the appropriate real number, printed to three decimals. Put a blank line after each test case, even after the last one.

样例输入:

2
0 0
3 4

3
17 4
19 4
18 5

0

样例输出:

Scenario #1
Frog Distance = 5.000

Scenario #2
Frog Distance = 1.414

思路分析:

        这一题其实读懂了题意之后,我们就会知道这一题是问从1号节点到2号节点中的路径中的边权的最大值的最小值,所以我们可以用求最短路径的算法来得出答案,如Floyd,dijkstra,SPFA等等都是可以的 ,我是用的最暴力,时间复杂度最高的Floyd(因为它可以求出所有的答案,暴力出奇迹)。

代码实现:

#include
#include
#include
#include
using namespace std;
struct node {
	int x,y;
} s[205];
int n,m,p;
double dp[205][205];
int read() {
	int x=0,f=1;
	char s=getchar();
	while(s<'0'||s>'9') {
		if(s=='-')
			f=-1;
		s=getchar();
	}
	while(s>='0'&&s<='9') {
		x*=10;
		x+=s-'0';
		s=getchar();
	}
	return x*f;
}
int main() {
	while(scanf("%d",&n)!=-1) {
		p ++ ;
		if(n==0) 
		{
			return 0;
		}
		for(int i=1; i<=n; i++) {
			s[i].x=read();
			s[i].y=read();
		}
		for(int i=1; i<=n; i++)
			for(int j=i; j<=n; j++)
				dp[i][j]=dp[j][i]=sqrt(double((s[i].x-s[j].x)*(s[i].x-s[j].x)+(s[i].y-s[j].y)*(s[i].y-s[j].y)));
		for(int k=1; k<=n; k++)
			for(int i=1; i<=n; i++)
				for(int j=1; j<=n; j++)
					dp[i][j]=min(dp[i][j],max(dp[i][k],dp[k][j]));
		printf("Scenario #%d\n",p);
		printf("Frog Distance = %.3f\n\n",dp[1][2]);
	}
}

 

你可能感兴趣的:(算法,数据结构,C++寒假学习专栏)