欢迎大家关注我的微信公众号(听烟柳),里面会不定时更新PAT-A/B程序代码~
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<iostream>
#include<algorithm>
#include<vector>
using namespace std;
#define maxn 510
#define Inf 0x3fffffff
int N,M,S,D;
int G[maxn][maxn],cost[maxn][maxn],dist[maxn];
vector<int > pre[maxn],path,optpath;
int value,optvalue=Inf;
bool vis[maxn];
void init()
{
for(int i=0;i<maxn;i++)
{
for(int j=0;j<maxn;j++)
{
G[i][j]=Inf;
cost[i][j]=0;
}
dist[i]=Inf;
vis[i]=false;
}
}
void Dijistra(int s)//利用迪杰斯特拉算法找到最短路径
{
dist[s]=0;
pre[s].push_back(s);
for(int i=0;i<N;i++)
{
int min=Inf,index=-1;
for(int j=0;j<N;j++)
{
if(dist[j]<min&&vis[j]==false)
{
min=dist[j];
index=j;
}
}
if(index==-1)
return;
vis[index]=true;
for(int j=0;j<N;j++)
{
if(dist[j]>dist[index]+G[index][j]&&G[index][j]!=Inf&&vis[j]==false)
{
dist[j]=dist[index]+G[index][j];
pre[j].clear();
pre[j].push_back(index);
}
else if(dist[j]==dist[index]+G[index][j]&&G[index][j]!=Inf&&vis[j]==false)
pre[j].push_back(index);
}
}
}
void DFS(int s,int d)//s为始发地,d为目的地
{
if(s==d)
{
path.push_back(s);
value=0;
for(int i=0;i<path.size()-1;i++)
value+=cost[path[i+1]][path[i]];
if(value<optvalue)
{
optvalue=value;
optpath=path;
}
path.pop_back();
return;
}
path.push_back(d);
for(int i=0;i<pre[d].size();i++)
DFS(s,pre[d][i]);
path.pop_back();
}
int main()
{
init();//对数据进行初始化
scanf("%d%d%d%d",&N,&M,&S,&D);
int c1,c2,distance,expense;
for(int i=0;i<M;i++)//输入高速公路的距离以及花费信息
{
scanf("%d%d%d%d",&c1,&c2,&distance,&expense);
G[c1][c2]=distance;
G[c2][c1]=distance;
cost[c1][c2]=expense;
cost[c2][c1]=expense;
}
Dijistra(S);
DFS(S,D);
for(int i=optpath.size()-1;i>=0;i--)
printf("%d ",optpath[i]);
printf("%d %d",dist[D],optvalue);
return 0;
}