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=
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
思路
我们反着建边,然后最短路。。
代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
const int N=1000+5;
const int M=20000+5;
const int INF=0x3f3f3f3f;
int t,s,n,m,map[N][N],vis[N],d[N];
void djstl(int s)
{
for (int i=1;i<=n;i++)
{
d[i]=i==s?0:map[s][i];
vis[i]=(i==s);
}
for (int i=1;i<n;i++)
{
int maxn=INF;int v=-1;
for (int j=1;j<=n;j++)
if (!vis[j]&&maxn>d[j]) {maxn=d[j];v=j;}
if (v==-1) continue;
vis[v]=1;
for (int j=1;j<=n;j++)
if (!vis[j]&&d[v]+map[v][j]<d[j]) d[j]=d[v]+map[v][j];
}
}
int main()
{
while(~scanf("%d %d %d",&n,&m,&s))
{
memset(map,INF,sizeof(map));
for (int i=0;i<m;i++)
{
int p,q,w;
scanf("%d %d %d",&p,&q,&w);
map[q][p]=min(map[q][p],w);
}
djstl(s);
scanf("%d",&t);
int maxn=INF;
for (int i=0;i<t;i++)
{
int e;
scanf("%d",&e);
maxn=min(maxn,d[e]);
}
if (maxn==INF) printf("-1\n");
else printf("%d\n",maxn);
}
return 0;
}