题目大意
一只青蛙在湖中1号石头上, 它想去2石头号上去找另外一只青蛙,但是 湖里的水很脏,它不愿意游泳,所以它要跳过去;
给出 两只青蛙所在石头的坐标, 及湖里其他石头的坐标;任一两个坐标点间都是双向连通的。显然从A到B存在至少一条的通路,每一条通路的元素都是这条通路中前后两个点的距离,这些距离中又有一个最大距离。
现在要求求出所有通路的最大距离,并把这些最大距离作比较,把最小的一个最大距离作为青蛙的最小跳远距离。
bfs+二分
//memory:254K time:32MS
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define MAX 205
#define inf 1e10
#define ll int
struct P {
double x, y;
P(double a = 0, double b = 0) { x = a, y = b; }
}arr[MAX];
double dis[MAX][MAX];
int vis[MAX], N, cnt = 1;
double dist(P p1, P p2) {
return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
}
//检查 最长距离为k时 是否可以到达终点
bool check(double k) {
memset(vis, 0, sizeof(vis));
if (dis[1][2] <= k)return true;
queue<ll> q; q.push(1);
while (!q.empty()) {
ll id = q.front(); q.pop(); vis[id] = 1;
if (dis[id][2] <= k)return true;
for (int i = 1; i <= N; i++) {
if (dis[id][i] <= k && !vis[i])
q.push(i);
}
}
return false;
}
int main() {
while (scanf("%d", &N) && N) {
double md = 0;
for (int k = 1; k <= N; k++)
scanf("%lf%lf", &arr[k].x, &arr[k].y);
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
dis[i][j] = dist(arr[i], arr[j]);
if (dis[i][j] > md)md = dis[i][j];
}
}
double l = 0, r = dis[1][2];
//因为要保留三位数
while (r - l > 0.00001) {
double mid = (l + r) / 2;
if (check(mid))r = mid;
else l = mid;
}
printf("Scenario #%d\n", cnt++);
printf("Frog Distance = %.3f\n\n", r);
}
}
dfs+二分
这道题竟然非常适合dfs,0MS就能过,仔细想想也是,这里使用dfs的话不需要任何回溯,一个点遍历过了就不用再管了。
memory:512K time:0MS
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define MAX 205
#define inf 1e10
#define ll int
struct P {
double x, y;
P(double a = 0, double b = 0) { x = a, y = b; }
}arr[MAX];
double dis[MAX][MAX];
int vis[MAX], N, cnt = 1;
double dist(P p1, P p2) {
return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
}
//检查 最长距离为k时 是否可以到达终点
bool check(double k, ll v) {
if (v == 2)return true;
vis[v] = 1;
for (int i = 1; i <= N; i++) {
if (!vis[i] && dis[v][i] <= k) {
if (check(k, i))return true;
}
}
return false;
}
int main() {
while (scanf("%d", &N) && N) {
double md = 0;
for (int k = 1; k <= N; k++)
scanf("%lf%lf", &arr[k].x, &arr[k].y);
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
dis[i][j] = dist(arr[i], arr[j]);
if (dis[i][j] > md)md = dis[i][j];
}
}
double l = 0, r = dis[1][2];
//因为要保留三位数
while (r - l > 0.00001) {
double mid = (l + r) / 2;
memset(vis, 0, sizeof(vis));
if (check(mid, 1))r = mid;
else l = mid;
}
printf("Scenario #%d\n", cnt++);
printf("Frog Distance = %.3f\n\n", r);
}
}
值得一提的是如果他会TLE那么我会选择用双向bfs,这道题其实用这个也蛮不错的。