PAT甲级-1030-Travel Plan(Dijkstra算法+最短路径)

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

此处是Dijkstra算法详解,可参考

代码如下

#include<iostream>
#include<climits> 
using namespace std;
const int N = 501;
int n,m,s,d;
int map[N][N],Cos[N][N];
int dis[N],cos[N],visit[N],pre[N];

void dfs(int v)
{
	if(v == s){
		cout<<v;
	}else{
		dfs(pre[v]);
		cout<<" "<<v;
	}
}
void dijsktra()
{
	dis[s] = 0;cos[s] = 0;
	for(int i = 0; i < n; i++)
	{
		int min=INT_MAX,index = -1;
		for(int j = 0;j < n; j++)
		{
			if(!visit[j] && dis[j] < min){
				min = dis[j];
				index = j;
			}
		}
		if(index == -1) break;
		visit[index] = 1;
		for(int j = 0; j < n; j++)
		{
			if(!visit[j]&&map[index][j]!=INT_MAX&&dis[j] > dis[index]+map[index][j]){
				dis[j] = dis[index]+map[index][j];
				cos[j] = cos[index]+Cos[index][j];
				pre[j] = index;
			}else if(map[index][j]!=INT_MAX&&dis[j] == dis[index]+map[index][j] && cos[j] > cos[index]+Cos[index][j]){
				cos[j] = cos[index]+Cos[index][j];
				pre[j] = index;
			}
		}
	}
}
int main()
{
	cin>>n>>m>>s>>d;
	fill(map[0],map[0]+N*N,INT_MAX);
	fill(Cos[0],Cos[0]+N*N,INT_MAX);
	fill(dis,dis+N,INT_MAX);
	fill(cos,cos+N,INT_MAX);
	fill(visit,visit+N,0);
	int x,y,dist,cost;
	for(int i = 0; i < m; i++)
	{
		cin>>x>>y>>dist>>cost;
		map[x][y] = map[y][x] = dist;
		Cos[x][y] = Cos[y][x] = cost;
	}
	dijsktra();
	dfs(d);
	cout<<" "<<dis[d]<<" "<<cos[d]; 
	return 0;
} 
发布了110 篇原创文章 · 获赞 746 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_42437577/article/details/104293480
今日推荐