PAT (Advanced) 1030. Travel Plan (30)

博客给出了一段C++代码,实现了Dijkstra算法。代码中定义了地图、距离、花费等数组,通过初始化和Dijkstra算法函数,计算从起点到终点的最短路径及最小花费,并输出路径和结果。还给出了代码的参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stack>

using namespace std;

const int INF = 0x6fffffff;
const int MAX = 501;

int map[MAX][MAX], value[MAX][MAX], dist[MAX], cost[MAX], pre[MAX], visit[MAX];
stack<int> path;

void init(int n)
{
	for (int i = 0; i < n; i++)
	{
		visit[i] = 0;
		pre[i] = -1;
		for (int j = 0; j < n; j++)
		{
			map[i][j] = INF;
			value[i][j] = INF;
		}
	}
}

void dijkstra(int start, int end, int n)
{
	int mind, v;
	for (int i = 0; i < n; i++)
	{
		dist[i] = map[start][i];
		cost[i] = value[start][i];
	}
	visit[start] = 1;
	
	for (int i = 1; i < n; i++)
	{
		mind = INF;
		for (int j = 0; j < n; j++)
		{
			if (visit[j] == 0 && dist[j] < mind)
			{
				mind = dist[j];
				v = j;
			}
		}
		visit[v] = 1;
		if (v == end)	return;
		for (int j = 0; j < n; j++)
		{
			if (visit[j] == 0 && map[v][j] < INF)
			{
				if (dist[j] > dist[v] + map[v][j])
				{
					dist[j] = dist[v] + map[v][j];
					cost[j] = cost[v] + value[v][j];
					pre[j] = v;
				}
				else if (dist[j] == dist[v] + map[v][j] && cost[j] > cost[v] + value[v][j])
				{
					cost[j] = cost[v] + value[v][j];
					pre[j] = v;
				}
			}
		}
	}
}

int main()
{
	int N, M, S, D;
	cin >> N >> M >> S >> D;
	init(N);
	int x, y, d, c;
	for (int i = 0; i < M; i++)
	{
		cin >> x >> y >> d >> c;
		if (map[x][y] > d)
		{
			map[x][y] = map[y][x] = d;
			value[x][y] = value[y][x] = c;
		}
		else if (map[x][y] == d && value[x][y] > c)
		{
			value[x][y] = value[y][x] = c;
		}
	}

	if (S == D)
	{
		cout << S << " " << D << "0 0" << endl;
		return 0;
	}
	dijkstra(S, D, N);
	int p = pre[D];
	while (p != -1)
	{
		path.push(p);
		p = pre[p];
	}
	cout << S;
	while (!path.empty())
	{
		cout << " " << path.top();
		path.pop();
	}
	cout << " " << D << " " << dist[D] << " " << cost[D] << endl;
}
参考: http://blog.youkuaiyun.com/iaccepted/article/details/21322745
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值