Subway POJ

 

题目链接:https://vjudge.net/problem/POJ-2502

思路:我们把家,学校,车站,都抽象成一个点,然后可以表示一张G(V,E)无向图。

这里我们要注意,相邻车站才可以相互以40km/h抵达,其他的只能以10km/h,再输入的时候要注意了。


  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstring>
  4 #include <algorithm>
  5 #include <cmath>
  6 #include <iomanip>
  7 using namespace std;
  8 
  9 typedef long long LL;
 10 #define inf (double)(1LL << 30) - 1
 11 #define rep(i,j,k) for(int i = (j); i <= (k); i++)
 12 #define rep__(i,j,k) for(int i = (j); i < (k); i++)
 13 #define per(i,j,k) for(int i = (j); i >= (k); i--)
 14 #define per__(i,j,k) for(int i = (j); i > (k); i--)
 15 
 16 const int N  = 210;
 17 const double v1 = 10000.0/60; //步行
 18 const double v2 = 40000.0/60; //车速
 19 double mp[N][N];
 20 double dis[N];
 21 bool vis[N];
 22 
 23 struct Point{
 24     double x,y;
 25 };
 26 Point node[N];
 27 
 28 void init(){
 29 
 30     rep__(i,1,N) rep__(j,1,N){
 31         if(i == j) mp[i][j] = 0;
 32         else mp[i][j] = inf; 
 33     }
 34 }
 35 
 36 //算两点距离
 37 inline double dist(Point a, Point b){
 38 
 39     return sqrt((a.x - b.x)*(a.x - b.x ) + (a.y - b.y)*(a.y - b.y));
 40 }
 41 
 42 double dijkstra(int cnt){
 43 
 44 
 45     rep(i,1,cnt) dis[i] = mp[1][i];
 46     vis[1] = true;
 47 
 48     rep(i,2,cnt){
 49         int index = -1;
 50         double v = inf;
 51 
 52         rep(j,1,cnt){
 53             if(!vis[j] && v > dis[j]) v = dis[index = j];
 54         }
 55 
 56         if(index == -1) continue;
 57 
 58         vis[index] = true;
 59 
 60         rep(j,1,cnt){
 61             if(!vis[j] && dis[j] > dis[index] + mp[index][j])
 62                 dis[j] = dis[index] + mp[index][j];
 63         }
 64     }
 65 
 66     return dis[2];
 67 }
 68 
 69 int main(){
 70     
 71     ios::sync_with_stdio(false);
 72     cin.tie(0);
 73     
 74     //初始化图
 75     init();
 76 
 77     cin >> node[1].x >> node[1].y >> node[2].x >> node[2].y; //1号为家,2号为学校
 78     
 79     int cnt = 2;
 80     bool flag = false;//判断是不是相邻的车站
 81 
 82     double x,y;
 83     while(cin >> x >> y){
 84 
 85         if(x == -1 && y == -1){ //到车站底了,标记之后不是相邻车站。
 86             flag = false;
 87             continue;
 88         }
 89         //每个点都存下来
 90         ++cnt;
 91         node[cnt].x = x;
 92         node[cnt].y = y;
 93 
 94         //相邻车站以v2前进,可以相互抵达
 95         if(flag){
 96             mp[cnt][cnt - 1] = mp[cnt - 1][cnt] = min(mp[cnt - 1][cnt], dist(node[cnt - 1],node[cnt])/v2);
 97         }
 98         flag = true;//标记为相邻车站
 99     }
100 
101     //所有点枚举v1速度到的时间去更新图的情况
102     rep(i,1,cnt){
103         rep(j,1,cnt)
104             mp[i][j] = min(mp[i][j], dist(node[i], node[j])/v1);
105     }
106 
107     //之后就是裸的dijkstra板子
108     cout << fixed << setprecision(0) << dijkstra(cnt) << endl;
109 
110     getchar();getchar();
111 
112     return 0;
113 }
原文地址:https://www.cnblogs.com/SSummerZzz/p/11240698.html