您的位置:首页 > 其它

poj Subway(dijkstra)

2017-02-21 19:44 260 查看
Subway

Description

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 -1

Sample Output
21


ps:注意两点:
1.最后的输入以EOF结束
2.只有在同一条地铁线上的相邻车站才能乘车,其他都需要按步行
代码:
#include<stdio.h>
#include<string.h>
#include<math.h>

#define maxn 200+10
const int inf=0x3f3f3f3f;
double map[maxn][maxn],d[maxn];
int x[maxn],y[maxn];
bool inq[maxn];
int ps;

void dijkstra(int st,int ed)
{
for(int i=1; i<maxn; i++)
{
d[i]=map[1][i];
inq[i]=0;
}
inq[st]=1;
int v;
for(int i=1; i<ps; i++)
{
int min=inf;
for(int j=1; j<=ps; j++)
if(!inq[j]&&d[j]<min)
min=d[j],v=j;
inq[v]=1;
for(int j=1; j<=ps; j++)
if(!inq[j]&&d[j]>d[v]+map[v][j])
d[j]=d[v]+map[v][j];
}
printf("%.0lf\n",d[ed]);
}

double walk(int i,int j)//步行
{
double length=sqrt((double)(x[i]-x[j])*(double)(x[i]-x[j])+(double)(y[i]-y[j])*(double)(y[i]-y[j]));
return 60*length/10000;
}

double subway(int i,int j)//乘车
{
double length=sqrt((double)(x[i]-x[j])*(double)(x[i]-x[j])+(double)(y[i]-y[j])*(double)(y[i]-y[j]));
return 60*length/40000;
}

int main()
{
int i,j;
for(i=1; i<maxn; i++)
for(j=1; j<maxn; j++)
i==j?map[i][j]=0:map[i][j]=map[j][i]=inf;
scanf("%d%d%d%d",&x[1],&y[1],&x[2],&y[2]);
map[1][2]=map[2][1]=walk(1,2);
int a,b;
j=0,ps=3;//j用来判断当前车站与前一个车站是否为同一条线上的
while(~scanf("%d%d",&a,&b))
{
if(a==-1&&b==-1)
j=0;
else
{
x[ps]=a,y[ps]=b;
for(i=1; i<ps-j; i++)
map[i][ps]=map[ps][i]=walk(ps,i);
for(i=ps-j; i<ps; i++)
map[i][ps]=map[ps][i]=subway(ps,i);
j=1,ps++;
}
}
ps--;
dijkstra(1,2);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: