water!https://www.patest.cn/contests/pat-a-practise/1030
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 Input4 5 0 3 0 1 1 20 1 3 2 30 0 3 4 10 0 2 2 20 2 3 1 20Sample Output
0 2 3 3 40题意:给N个城市M条边,起点S终点D,每行给两个城市间距离和边权,求最短距离及路径,如果有多条最短路径,取边权和最小的那条(别忘了弄个pre数组存路径)。
↓
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxv = 555;
const int inf = 99999999999;
int mp[maxv][maxv],cost[maxv][maxv],d[maxv],c[maxv],pre[maxv];
bool vis[maxv]={false};
int N,M,S,D,c1,c2,dis,co;
void dijkstra(int st)
{
fill(d,d+maxv,inf);
fill(c,c+maxv,inf);
for(int i=0;i<N;i++) pre[i]=i;
d[st]=0;
c[st]=0;
for(int i=0;i<N;i++)
{
int u=-1,min=inf;
for(int j=0;j<N;j++)
{
if(vis[j]==false&&d[j]<min)
{
u=j;
min=d[j];
}
}
if(u==-1) return;
vis[u]=true;
for(int v=0;v<N;v++)
{
if(vis[v]==false&&mp[u][v]!=inf)
{
if(d[u]+mp[u][v]<d[v])
{
d[v]=d[u]+mp[u][v];
c[v]=c[u]+cost[u][v];
pre[v]=u;
}
else if(d[u]+mp[u][v]==d[v])
{
if(c[u]+cost[u][v]<c[v])
{
c[v]=c[u]+cost[u][v];
pre[v]=u;
}
}
}
}
}
}
void showpath(int x)
{
if(x==S)
{
printf("%d ",x);
return;
}
showpath(pre[x]);
printf("%d ",x);
}
int main()
{
scanf("%d%d%d%d",&N,&M,&S,&D);
fill(mp[0],mp[0]+maxv*maxv,inf);
fill(cost[0],cost[0]+maxv*maxv,inf);
for(int i=1;i<=M;i++)
{
scanf("%d%d%d%d",&c1,&c2,&dis,&co);
mp[c1][c2]=mp[c2][c1]=dis;
cost[c1][c2]=cost[c2][c1]=co;
}
dijkstra(S);
showpath(D);
printf("%d %d",d[D],c[D]);
return 0;
}