标签:ted attribute tar lex += ott down std nat
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.
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (≤) 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.
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.
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
0 2 3 3 40
#include<bits/stdc++.h> using namespace std; const int maxn=1010; #define inf 0x3fffffff int G[maxn][maxn]; int GP[maxn][maxn];//记录每条路的花费 int path[maxn]; bool collected[maxn]; int dist[maxn];//源点到该点的最短距离 int price[maxn];//记录源点到该点的花费 int n,m,s,d; void dijkstra(int s){ dist[s]=0; price[s]=0; for(int i=0;i<n;i++){ int v,mind=inf,minv=-1; for(int i=0;i<n;i++){ if(collected[i]==false&&dist[i]<mind){ mind=dist[i]; minv=i; } } v=minv; if(v==-1){ return ; } collected[v]=true; for(int i=0;i<n;i++){ if(collected[i]==false&&G[v][i]!=inf){ if(dist[v]+G[v][i]<dist[i]){ dist[i]=dist[v]+G[v][i]; path[i]=v; price[i]=price[v]+GP[v][i]; // printf("%d %d\n",i,price[i]); } else if(dist[v]+G[v][i]==dist[i]){ if(price[v]+GP[v][i]<price[i]){ price[i]=GP[v][i]+price[v]; path[i]=v; // printf("%d %d\n",i,price[i]); } } } } } } int main(){ fill(dist,dist+maxn,inf); fill(GP[0],GP[0]+maxn*maxn,inf); fill(path,path+maxn,-1); fill(collected,collected+maxn,false); fill(price,price+maxn,inf); fill(G[0],G[0]+maxn*maxn,inf); scanf("%d %d %d %d",&n,&m,&s,&d); for(int i=0;i<m;i++){ int a,b,c,e; scanf("%d %d %d %d",&a,&b,&c,&e); G[a][b]=c; G[b][a]=c; GP[a][b]=e; GP[b][a]=e; } dijkstra(s); int k[maxn]; int i=1; k[0]=d; int g=d; while(path[g]!=-1){ k[i]=path[g]; g=path[g]; i++; } int sumPath=0; for(int j=i-1;j>0;j--){ sumPath+=G[k[j]][k[j-1]]; } for(int j=i-1;j>=0;j--){ printf("%d ",k[j]); } printf("%d ",sumPath); printf("%d\n",price[d]); return 0; }
标签:ted attribute tar lex += ott down std nat
原文地址:https://www.cnblogs.com/dreamzj/p/14359845.html