题目:http://pta.patest.cn/pta/test/15/exam/4/question/717
PTA - 数据结构与算法题目集(中文) - 5-9
有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
3 40
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int maxl=505;
const double maxd=1000;
struct lu
{
int post;
int dis;
int cost;
};
int n,m,s,d;
vector<lu> G[maxl]; //邻接表存储图
//dijkstra
int dist[maxl];
int cost[maxl];
bool vis[maxl];
void dijkstra(int s)
{
//初始化
for(int i=0; i<n; i++)
{
dist[i]=maxd;
cost[i]=maxd;
vis[i]=false;
}
dist[s]=0;
cost[s]=0;
vis[s]=true; //!
//开始dp
int v=s;
int w;
while(v!=d)
{
for(unsigned int i=0; i<G[v].size(); i++)
{
w=G[v][i].post;
int dis=G[v][i].dis;
int cos=G[v][i].cost;
if( !vis[w] ) //未被访问过
{
if(dist[v]+dis < dist[w])
{
dist[w]=dist[v]+dis;
cost[w]=cost[v]+cos;
}
else if(dist[v]+dis == dist[w])
{
if(cost[v]+cos < cost[w])
cost[w]=cost[v]+cos;
}
}
}
//找从v出发经最短距离到达的点
int mindis=maxd;
for(int i=0; i<n; i++)
{
if(dist[i]<mindis && !vis[i]) //注:!vis[i]
{
mindis=dist[i];
v=i; //更新 v
}
}
vis[v]=true; //以新的v为起点。将其标记为true
}//while
}
int main()
{
//int n,m,s,d;
lu newLu;
int pre;
cin >> n >> m >> s >> d;
while(cin >> pre)
{
cin >> newLu.post >> newLu.dis >> newLu.cost;
G[pre].push_back(newLu);
int tmp=pre; //交换pre和post
pre=newLu.post;
newLu.post=tmp;
G[pre].push_back(newLu);
}
dijkstra(s);
cout << dist[d] << " " << cost[d] << endl;
return 0;
}