POJ-2387 Til the Cows Come Home

本文介绍了一种解决单源最短路径问题的算法——Dijkstra算法,并通过具体实例展示了如何利用该算法找到从起点到终点的最短路径。特别讨论了如何通过松弛操作更新路径权值。

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

##最短路问题

题目大意:
有好多相通的路,路都有一定的长度,求1 到 n 的最短距离,单源最短路

https://vjudge.net/problem/POJ-2387 链接

dijkstra :

思路就是贪心 从节点1 找 ,如果 节点i 到1 的距离 > 节点1到节点u + 节点u和节点i的距离 ,更新路径权值,这个算法只能计算单元最短路,而且不能计算负权值,
path数组储存节点1到各个节点的距离,所以初始化path[1] = 0; 其他的都是INF 然后不断更新
比如1到3的最短路就是比较path[3]与path[2]+cost[2][3],如果大于的话就更新path[3] = path[2]+cost[2][3],这个专业术语叫松弛,这种算法的核心思想就是通过边来松弛一号顶点到其他定点的路程

#include<iostream>
#include<string>
#include<cstring>

struct NOD
{
	int from, to, cost;
}es[4040];

int path[1010];
const int INF = 0x3f3f3f3f;

void short_path(int t)
{
	memset(path, 0x3f, sizeof path);
	path[1] = 0;
	while(true)
	{
		bool step = false;
		for(int i = 0; i < 2*t; ++i)
		{
			if(path[es[i].from] != INF && path[es[i].to] > path[es[i].from] + es[i].cost)
			{
				step = true;
				path[es[i].to] = path[es[i].from] + es[i].cost;
			}
		}
		if(!step) break;
	}
}


int main()
{
	int n, t;
	std::cin >> t >> n;
	for(int i=0; i < t; ++i)
	{
		std::cin >> es[i].from >> es[i].to >> es[i].cost;
		es[i+t].from = es[i].to;
		es[i+t].to = es[i].from;
		es[i+t].cost = es[i].cost;
	}
	short_path(t);
	std::cout << path[n] << std::endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值