当前位置: 代码迷 >> 综合 >> Choose the best route ( dijkstra 路径翻转 )
  详细解决方案

Choose the best route ( dijkstra 路径翻转 )

热度:95   发布时间:2023-11-23 12:47:50.0

Choose the best route

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

题意就是求最短路,dijkstra 算法就可以,但是,是个多起点最短路,若每次根据起点来跑一次最短路,一般都会超时,因此路径翻转,将终点变为起点,求每个点的最短路的话,只跑一次就可以了

AC代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII; 
const int N=1010;
int n,m,s,w;
int g[N][N];
int dist[N];
int cost[N];
bool vis[N];void dijkstra()
{
    memset(dist,0x3f,sizeof dist);memset(vis,0,sizeof vis);dist[s]=0;for(int i=1;i<=n;i++){
    int x=-1;for(int j=1;j<=n;j++){
    if(!vis[j]&&(x==-1||dist[x]>dist[j]))x=j;}if(x==-1) return ;vis[x]=1;for(int j=1;j<=n;j++){
    dist[j]=min(dist[j],dist[x]+g[x][j]);}}
}int main()
{
    while(scanf("%d%d%d",&n,&m,&s)!=EOF){
    memset(g,0x3f,sizeof g);for(int i=1;i<=m;i++){
    int a,b,c;scanf("%d%d%d",&a,&b,&c);g[b][a]=min(g[b][a],c);}cin>>w;dijkstra();int ans=0x3f3f3f3f;for(int i=1;i<=w;i++){
    int x;scanf("%d",&x);ans=min(ans,dist[x]);}if(ans==0x3f3f3f3f) cout<<-1<<endl;else cout<<ans<<endl;}return 0;
}

题目卡了 cin 和 cout ,一开始用的 cin 和 cout 结果无限超时,后来改成scanf 后就过掉了,题目应该是卡了个时间限制。

  相关解决方案