您的位置:首页 > 其它

pat甲级1030. Travel Plan (30)

2018-03-15 12:34 459 查看

1030. Travel Plan (30)

时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
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 Costwhere 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

算法设计:

题目比较简单,使用Dijkstar算法求出符合要求的最短路径,利用DFS算法输出该路径即可,具体实现可见代码

c++代码:

#include<bits/stdc++.h>
using namespace std;
//边的类
struct Edge{
int v;//该边末端结点编号
int dis;//该边距离
int cost;//该边权重
Edge(int vv,int d,int c):v(vv),dis(d),cost(c){}//构造函数
};
vector<vector<Edge>>graph(505);//图
int dis[505];//存储起点到该点的最短距离
int cost[505];//存储起点到该点的最小权重
bool visit[505];//存储起点到该点是否已被访问
int pathLast[505];//存储起点到该点的父节点
int N,M,S,D;
void Dijkstra(){
while(!visit[D]){//如果终点还没有被访问到
//在当前未访问的结点中找到距离最小的结点
int v=-1,MIN=INT_MAX;
for(int i=0;i<N;++i){
if(!visit[i]&&dis[i]<MIN){
MIN=dis[i];
v=i;
}
}
if(v==-1) return;//该图不是连通图,直接返回
visit[v]=true;//置该点已被访问
//遍历该点能够到达的结点并更新相关信息
for(int i=0;i<graph[v].size();++i){
int temp=graph[v][i].v;
if(!visit[temp]&&dis[temp]>dis[v]+graph[v][i].dis){
dis[temp]=dis[v]+graph[v][i].dis;
cost[temp]=cost[v]+graph[v][i].cost;
pathLast[temp]=v;
}else if(dis[temp]==dis[v]+graph[v][i].dis&&
cost[temp]>cost[v]+graph[v][i].cost){
cost[temp]=cost[v]+graph[v][i].cost;
pathLast[temp]=v;
}
}
}
}
//深度优先遍历输出最短路径
void DFS(int v){
if(v==S)
printf("%d",v);
else{
DFS(pathLast[v]);
printf(" %d",v);
}
}
int main(){
scanf("%d%d%d%d",&N,&M,&S,&D);
for(int i=0;i<M;++i){
int a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
graph[a].push_back(Edge(b,c,d));
graph[b].push_back(Edge(a,c,d));
}
fill(dis,dis+N,INT_MAX);
fill(cost,cost+N,INT_MAX);
dis[S]=cost[S]=0;
Dijkstra();
DFS(D);
printf(" %d %d",dis[D],cost[D]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: