Think 求 最短 路径问题。。 第一想到的就是 Floyd 算法, 所以就尝试做了次。
PRoblem Description 平面上有n个点(n<=100),每个点的坐标均在-10000~10000之间。其中的一些点之间有连线。若有连线,则表示可从一个点到达另一个点,即两点间有通路,通路的距离为两点间的直线距离。现在的任务是找出从一点到另一点之间的最短距离。 Input 第1行为整数n。 第2行到第n+1行(共n行),每行两个整数x和y,描述了一个点的坐标(以一个空格分隔)。 第n+2行为一个整数m,表示图中连线的个数。 此后的m行,每行描述一条连线,由两个整数i和j组成,表示第1个点和第j个点之间有连线。 最后一行:两个整数s和t,分别表示源点和目标点。 Output 仅1行,一个实数(保留两位小数),表示从s到t的最短路径长度。 Example Input
5 0 0 2 0 2 2 0 2 3 1 5 1 2 1 3 1 4 2 5 3 5 1 5
Example Output
3.41
#include<bits/stdc++.h>#define MAX 0x3f3f3f;using namespace std;struct node{ int x, y;}a[1050];double Floyd (int x, int y, int n);double sum (int a, int b);double Map[1050][1050];double dis[1050][1050];int main() { int i, j; int x, y, k; int A, B; int n; double ans; cin >> n; memset(Map, 0, sizeof(Map)); memset(dis, 0, sizeof(dis)); for (i = 1;i <= n;i ++) { for (j = 1;j <= n;j ++) { if (i == j) Map[i][j] = 0; else Map[i][j] = Map[j][i] = MAX; } } for (i = 1;i <= n ;i ++) { cin >> a[i].x >> a[i].y; } cin >> k; for (i = 1;i <= k;i ++) { cin >> A >> B; if (Map[A][B] > sum(a[A].x - a[B].x, a[A].y - a[B].y)) { Map[A][B] = sum(a[A].x - a[B].x, a[A].y - a[B].y); Map[B][A] = sum(a[A].x - a[B].x, a[A].y - a[B].y); } } cin >>x >> y; ans = Floyd(x, y , n); cout << fixed << setprecision(2) << ans << endl; //限制小数位数 return 0; } double Floyd (int x, int y, int n) { int i, j, k; for (i = 0;i <= n;i ++) { for (j = 0;j <= n;j ++) { dis[i][j] = Map[i][j]; } } for (k = 1;k <= n;k ++) { for (i = 1;i <= n;i ++) { for (j = 1;j <= n;j ++) { if (i != j) dis[i][j] = min(dis[i][j], dis[k][i] + dis[k][j]); } } } return dis[x][y]; } double sum (int a, int b) { return sqrt(a*a + b*b); }/***************************************************User name: Result: AcceptedTake time: 8msTake Memory: 17404KBSubmit time: 2017-02-20 09:40:29****************************************************/新闻热点
疑难解答