题目链接:http://acm.zzu.edu.cn:8000/problem.php?id=10496
10496: Cross the River
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 62 Solved: 8
[ Submit][ Status][ Web Board]
Description
A frog wants to cross the river.The frog’s plane is determined by a rectangular coordinate system.The two sides of the river are respectively corresponding to the line y=0 and y=d (d>0).The frog is located in any coordinate which satisfies y<=0.The frog’s hop distance has a limit W.Now it wants to jump to the other side through the lotus leaves.Please select a reasonable route to minimize the journey.
Input
There are multiple test cases and the first line is the number of test cases T(1<=T<=10). For each test case,first line contains three integers d,w and n(0<d,w<=30000,0<n<=500,n is the number of lotus leaves), and in next n lines, the ith line contains the coordinate of the ith lotus leaf (xi,yi).(xi and yi are integers, and 0<yi<d )
Output
For each test case, output one line, the minimum of the distance.(The result keeps five decimal places)
If the frog can’t touch the other side,print “-1”.
Sample Input
16 3 21 22 4
Sample Output
6.23607
HINT
Source
题目解析: 野_最短路, 变换下直接 dij 就可以了
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 1009
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
typedef long long LL;
using namespace std;
struct node
{
int x, y;
}T[N];
double mp[N][N], dis[N];
int book[N];
double dij(int n)
{
int i, j;
memset(book, 0, sizeof(book));
for(i = 0; i <= n; i++) dis[i] = mp[0][i];
book[0] = 1; dis[0] = 0;
for(i = 0; i <= n; i++)
{
int m; double f = inf;
for(j = 0; j <= n; j++) if(!book[j] && dis[j] < f) f = dis[m = j];
if(f > inf - 1) break;
book[m] = 1;
for(j = 0; j <= n; j++)
{
if(!book[j] && dis[j] > dis[m] + mp[m][j])
dis[j] = mp[m][j] + dis[m];
}
}
return dis[n];
}
int main()
{
int t, d, w, n;
int i, j;
scanf("%d", &t);
while(t--)
{
scanf("%d%d%d", &d, &w, &n);
for(i = 1; i <= n; i++) scanf("%d%d", &T[i].x, &T[i].y);
for(i = 1; i <= n; i++)
{
if(T[i].y > w) mp[0][i] = mp[i][0] = inf;
else mp[0][i] = mp[i][0] = T[i].y;
if(d - T[i].y > w) mp[n+1][i] = mp[i][n+1] = inf;
else mp[n+1][i] = mp[i][n+1] = d - T[i].y;
}
if(d > w) mp[0][n+1] = mp[n+1][0] = inf;
else mp[0][n+1] = mp[n+1][0] = d;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
double k = sqrt(1.0 * (T[i].x - T[j].x) * (T[i].x - T[j].x) + (T[i].y - T[j].y) * (T[i].y - T[j].y));
if(k > w)
mp[i][j] = mp[j][i] = inf;
else mp[i][j] = mp[j][i] = k;
}
}
double ans = dij(n + 1);
if(ans > inf - 1) printf("-1\n");
else printf("%.5f\n", ans);
}
return 0;
}