题目链接:............
思路:岛为起点,把每个两个坐标距离小于人能跳的距离加入图中(用邻接矩阵存),点到岸边的距离小于人能跳得距离也加入图中,就成了最短路问题(这里用dijkstra算法)。
code:
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> typedef struct { int v, next; double w; }node; node edge[40000]; int n = 0, k = 0, coor[105][2], head[102], used[102], step[102]; double dist[10200], d = 0; void add(int u, int v, double w) { edge[k].v = v; edge[k].w = w; edge[k].next = head[u]; head[u] = k++; } void dijkstar() { int i = 0, j = 0, cur = 0, l = 0; double min = 0; for(i = 0; i<=n+1; i++) dist[i] = 1234567890; for(cur = head[0]; cur != -1; cur = edge[cur].next) { step[edge[cur].v] = 1; dist[edge[cur].v] = edge[cur].w; } for(i = 0; i<=n+1; i++) { min = 1234567890; for(j = 0; j<=n+1; j++) if(min>dist[j] && !used[j]) { min = dist[j]; l = j; } used[l] = 1; for(cur = head[l]; cur != -1; cur = edge[cur].next) { if(!used[edge[cur].v] && dist[edge[cur].v]>dist[l]+edge[cur].w) { dist[edge[cur].v] = dist[l]+edge[cur].w; step[edge[cur].v] = step[l]+1; } else if(dist[edge[cur].v] == dist[l]+edge[cur].w && step[edge[cur].v] > step[l]+1)//到达这点的距离相同,选步数少的那个 step[edge[cur].v] = step[l]+1; } } } int main() { int i = 0, j = 0, min = 0; double dis = 0; while(scanf("%d %lf",&n,&d) != EOF) { k = 0; memset(used, 0, sizeof(used)); memset(head, -1, sizeof(head)); for(i = 1; i<=n; i++) { scanf("%d %d",&coor[i][0], &coor[i][1]); dis = sqrt(pow(coor[i][0],2)+pow(coor[i][1],2)); if(dis-7.5<=d) add(0, i, dis-7.5); } for(i = 1; i<=n; i++)//转化为图 for(j = 1; j<=n; j++) { if(i == j) continue; dis = sqrt((coor[i][0]-coor[j][0])*(coor[i][0]-coor[j][0])+(coor[i][1]-coor[j][1])*(coor[i][1]-coor[j][1])); if(dis<=d) add(i, j, dis); } for(i = 1; i<=n; i++)//点到岸边的路径转化为图 { min = 50-coor[i][0]; if(min>50-coor[i][1]) min = 50-coor[i][1]; if(min>50+coor[i][0]) min = 50+coor[i][0]; if(min>50+coor[i][1]) min = 50+coor[i][1]; if(min<=d) add(i, n+1, min); } if(d>=42.50) printf("42.50 1\n"); else { dijkstar(); if(dist[n+1] == 1234567890) printf("can't be saved\n"); else printf("%.2lf %d\n",dist[n+1], step[n+1]); } } return 0; }