PAT甲級1030 Travel Plan

小王子y發表於2020-10-14

1030 Travel Plan (30分)
A traveler’s map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.

Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (≤500) is the number of cities (and hence the cities are numbered from 0 to N−1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:

City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.

Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.

Sample Input:

4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20

Sample Output:

0 2 3 3 40
#include<bits/stdc++.h>
using namespace std;
const int maxn=510;
const int INF=0x3fffffff;
int  G[maxn][maxn],cost[maxn][maxn];
int weight[maxn],n,m,st,ed;
int d[maxn],w[maxn],num[maxn],pre[maxn];
bool vis[maxn]={false};
void Dijkstra(int s){
  fill(d,d+maxn,INF);
  d[s]=0;
  w[s]=0;
  num[s]=1;
  for(int i=0;i<n;i++){
      int u=-1,MIN=INF;
      for(int j=0;j<n;j++){
          if(!vis[j]&&d[j]<MIN){
             u=j;
             MIN=d[j];
          }
      }
      if(u==-1)break;
      vis[u]=true;
      for(int v=0;v<n;v++){
          if(!vis[v]&&G[u][v]!=INF){
                if(d[u]+G[u][v]<d[v]){
                d[v]=d[u]+G[u][v];
                num[v]=num[u];
                w[v]=w[u]+cost[u][v];
                pre[v]=u;
          } else if(d[u]+G[u][v]==d[v]){
                     if(w[u]+cost[u][v]<w[v]){
                     w[v]=w[u]+cost[u][v];
                     pre[v]=u;
                 }
                     num[v]+=num[u];  //無論如何都得加
          } 
        }
       }
     }
   }
void dfs(int v){
 if(v==st){
   printf("%d",v);
   return;
 }
    dfs(pre[v]);
    printf(" %d",v);
}
int main(){
    cin>>n>>m>>st>>ed;
    fill(G[0],G[0]+maxn*maxn,INF);
    while(m--){
        int a,b,c,d;
        cin>>a>>b>>c>>d;
        G[a][b]=c;
        G[b][a]=c;
        cost[a][b]=d;
        cost[b][a]=d;
    }
     Dijkstra(st);
     dfs(ed);
     printf(" %d %d\n",d[ed],w[ed]);
     return 0;
}

相關文章