You have just moved from a quiet Waterloo neighbourhood to a big, noisy city. Instead of getting to ride your bike to school every day, you now get to walk and take the subway. Because you don't want to be late for class, you want to know how long it will take you to get to school.
You walk at a speed of 10 km/h. The subway travels at 40 km/h. Assume that you are lucky, and whenever you arrive at a subway station, a train is there that you can board immediately. You may get on and off the subway any number of times, and you may switch between different subway lines if you wish. All subway lines go in both directions.Input
Input consists of the x,y coordinates of your home and your school, followed by specifications of several subway lines. Each subway line consists of the non-negative integer x,y coordinates of each stop on the line, in order. You may assume the subway runs in a straight line between adjacent stops, and the coordinates represent an integral number of metres. Each line has at least two stops. The end of each subway line is followed by the dummy coordinate pair -1,-1. In total there are at most 200 subway stops in the city.
Output
Output is the number of minutes it will take you to get to school, rounded to the nearest minute, taking the fastest route.
Sample Input
0 0 10000 1000 0 200 5000 200 7000 200 -1 -1 2000 600 5000 600 10000 600 -1 -1Sample Output
21题意:你到一个大城市,现在上学你可以步行和乘地铁,你以每小时10公里的速度行走。地铁以每小时40公里的速度运行。当你到达地铁站时,一列火车就在那里,你可以立即上车。你可以在地铁上和下任意次数,你可以在不同的地铁线路之间切换。所有的地铁线路都是双向的。输出到学校的最短时间。
分析:建一个二维数组记录俩点间的时间,因为要精确到分钟,所以还要把步行和地铁的速度转化为m/min,方便时间运算。只要把地铁间的时间放入二维数组里,只需处理一次,用俩个for循环计算所有点的之间的步行速度,要用min来放入最短时间,这样就不会代替地铁之间的时间,因为地铁之间的时间肯定比步行用的时间少。
代码:
#include<cstdio> #include<cstring> #include<iostream> #include<cmath> using namespace std; const int maxn=550; const int inf=0x3f3f3f3f; double map[maxn][maxn],dis[maxn]; //俩点之间所用的时间 int book[maxn]; struct node { int x; int y; } q[maxn]; void init() { for(int i=1; i<maxn; i++) for(int j=1; j<maxn; j++) if(i==j)map[i][j]=0; else map[i][j]=inf; } double Dis(int i,int j) { return sqrt(1.0*(q[i].x-q[j].x)*(q[i].x-q[j].x)+(q[i].y-q[j].y)*(q[i].y-q[j].y)); } double Distra(int st,int n) //dijkstra { for(int i=1; i<=n; i++) dis[i]=map[st][i]; memset(book,0,sizeof(book)); for(int i=1; i<n; i++) { double mini=inf; int k=-1; for(int j=1; j<=n; j++) if(!book[j]&&dis[j]<mini) { mini=dis[j]; k=j; } if(k==-1) break; book[k]=1; for(int j=1; j<=n; j++) if(!book[j]&&dis[j]>dis[k]+map[k][j]) dis[j]=dis[k]+map[k][j]; } return dis[2]; } int main() { double v1=40000.0/60.0; //地铁速度 double v2=10000.0/60.0; //步行速度 init(); scanf("%d%d%d%d",&q[1].x,&q[1].y,&q[2].x,&q[2].y); int n=3,last=3; while(scanf("%d%d",&q[n].x,&q[n].y)!=EOF) { if(q[n].x==-1&&q[n].y==-1) { last=n; continue; } if(last!=n) map[n-1][n]=map[n][n-1]=Dis(n-1,n)/v1; //存入地铁之间的时间 n++; } n--; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) map[i][j]=min(map[i][j],Dis(i,j)/v2); //存步行的时间 printf("%.0f\n",Distra(1,n)); return 0; }