dijkstra最短路经算法简单模板(单源)


Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.
Input
* Line 1: Two integers: T and N

* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.
Output
* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.
Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
int vis[1005],dis[1005],cost[1005][1005];//vis为标记跳板点,dis为每个点与起点的距离,cost为记录点与点的权值, 
int n,m,k;
void dij(int s)
{
	vis[s]=1;//标记已充当过跳板的点,刚开始时,第一个起点为跳板点 
	for(int i=1;i<n;i++)
	{
		int k=1e9-1;//设置k为很大很大的一个数字 
		for(int j=1;j<=n;j++)
		{
			if(!vis[j] && dis[j]<k)//找出距离跳板最近的点并且这个点没有充当过跳板 
			{
				k=dis[j]; //更新k的值,找出距离当前跳板最近的点 
				s=j;//记录当前跳板 
			}
		}
		vis[s]=1;//标记当前跳板,下次寻找过程中,不在使用这个跳板 
		for(int i=1;i<=n;i++)
		{
			dis[i]=min(dis[i],dis[s]+cost[s][i]);//当前跳板为s点,判断原来每个点与起点的距离最近,
			                                     //还是起点通过跳板与每个点的距离哪儿个更近,这个过程称为松弛 
		}
	}
	cout<<dis[n];
}
int main()
{
	int a,b,c,k,t,sum=0.0;
	memset(vis,0,sizeof(vis));//初始化每个点为0,如果充当跳板则赋值为1 
	memset(cost,0x3f,sizeof(cost));//初始化每两个点之间的距离为无穷大 
	cin>>m>>n;
	for(int i=1;i<=n;i++)
	{
		cost[i][i]=0;//自身与自身的距离为0 
		dis[i]=cost[1][i];//初始化每个点与起点的距离为无穷大 
	}
	for(int i=1;i<=m;i++)
	{
		cin>>a>>b>>c;
		cost[a][b]=min(cost[a][b],c);//无方图,a点到b点的距离,为c; 
		cost[b][a]=min(cost[b][a],c);//无方图,b点到a点的距离,为c; 
	}
	dij(1);
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值