Choose the best route
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 22019 Accepted Submission(s): 7036
Problem Description
One day , Kiki wants to visit one of her friends. As she is liable to carsickness , she wants to arrive at her friend’s home as soon as possible . Now give you a map of the city’s traffic route, and the stations which are near Kiki’s home so that she can take. You may suppose Kiki can change the bus at any station. Please find out the least time Kiki needs to spend. To make it easy, if the city have n bus stations ,the stations will been expressed as an integer 1,2,3…n.
Input
There are several test cases.
Each case begins with three integers n, m and s,(n<1000,m<20000,1=<s<=n) n stands for the number of bus stations in this city and m stands for the number of directed ways between bus stations .(Maybe there are several ways between two bus stations .) s stands for the bus station that near Kiki’s friend’s home.
Then follow m lines ,each line contains three integers p , q , t (0<t<=1000). means from station p to station q there is a way and it will costs t minutes .
Then a line with an integer w(0<w<n), means the number of stations Kiki can take at the beginning. Then follows w integers stands for these stations.
Output
The output contains one line for each data set : the least time Kiki needs to spend ,if it’s impossible to find such a route ,just output “-1”.
Sample Input
5 8 5 1 2 2 1 5 3 1 3 4 2 4 7 2 5 6 2 3 5 3 5 1 4 5 1 2 2 3 4 3 4 1 2 3 1 3 4 2 3 2 1 1
Sample Output
1 -1
思路:假设从0点开始,可以直接出发的点 距离即为0,转化成从0点到n的裸迪杰斯特拉最短路问题。
#include <iostream>
#include <algorithm>
#include <math.h>
#include <vector>
#include<cstdio>
#include <cstring>
#include <queue>
#include <map>
#include <string.h>
#include<bitset>
typedef long long ll;
using namespace std;
const int inf=0x3f3f3f3f;
//int inf = 2e7+100;
int n,m,e;
int G[2222][2222];
int vis[1111],d[1111],p[1111];
void dji()
{
memset(vis,0,sizeof(vis));
vis[0]=1;
for(int i=0;i<=n;i++)
{
d[i]=G[0][i];
}
for(int i=0;i<=n;i++)
{
int u=-1,mi=inf;
for(int j=0;j<=n;j++)
{
if(!vis[j]&&d[j]<mi)
{
mi=d[j];
u=j;
}
}
if(u==-1)
break;
vis[u]=1;
for(int j=0;j<=n;j++)
{
if(!vis[j]&&d[j]>d[u]+G[u][j])
{
d[j]=d[u]+G[u][j];
}
}
}
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&e))
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<=n;j++)
{
G[i][j]=inf;
}
}
for(int i=1;i<=m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(c<G[a][b])
{
G[a][b]=c;
}
}
int ans;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
int t;
scanf("%d",&t);
G[0][t]=0;
}
dji();
ans=d[e];
if(ans==inf)
printf("-1\n");
else
printf("%d\n",ans);
}
return 0;
}
博客围绕选择最佳路线问题展开,给出城市公交站交通路线相关信息,包括站点数、路线数、各路线耗时等,要求找出Kiki到达朋友家的最少用时。思路是将问题转化为从0点到n的裸迪杰斯特拉最短路问题进行求解。
206

被折叠的 条评论
为什么被折叠?



