最短路dijkstra模板+路径还原

typedef long long LL;
const LL INF = 0x3f3f3f3f;
LL cost[2010][2010]; //两个之间没有边,值为INF,这个操作是在输入边之前完成
LL d[2010]; //d[i]表示从源点到第i点的最短距离
bool used[2010]; //判断下标为i的点是否使用
LL V,E;//V为点的个数,E为边的个数
void dijkstra(LL s) //s是源点
{
	memset(d, INF, sizeof(d));  //初始化
	memset(used, 0, sizeof(used));//初始化
	d[s] = 0; //源点与自身的距离为0
	while (1)
	{
		LL v = -1; //判断是否还存在尚未使用的点
		for (LL u = 0; u < V; u++)
		{
			if (!used[u] && (v == -1 || d[u] < d[v])) v = u; //从尚未使用过的顶点中选择一个距离最小的顶点
		}
		if (v == -1) break; //全都使用了,退出
		used[v] = 1; //标记为使用了
		for (LL u = 0; u < V; u++) //遍历所有点,更新单源最短路
		{
			d[u] = min(d[u], d[v] + cost[v][u]);
		}
	}
}

路径还原
在求解最短距离时,满足d[j]=d[k]+cost[k][j]的顶点k, 就是最短路上顶点j的前趋节点,因此通过不断寻找前趋节点就可以恢复出最短路。
我们用pre[j]来记录最短路上顶点j的前驱。在d[j]被d[j]=d[k]+cost[k][j]更新时,修改pre[j]=k,这样就可以求得pre数组。在计算从s出发到j的最短路时,通过pre[j]就可以知道顶点j的前趋,因此不断把j替换成pre[j]直到j=s为止就可以了。

加上路径输出后的完整代码

typedef long long LL;
const LL INF = 0x3f3f3f3f;
LL cost[2010][2010]; //两个之间没有边,值为INF,这个操作是在输入边之前完成
LL d[2010]; //d[i]表示从源点到第i点的最短距离
bool used[2010]; //判断下标为i的点是否使用
LL V, E;//V为点的个数,E为边的个数
LL pre[2010];
void dijkstra(int s)
{
	memset(d, INF, sizeof(d));  
	memset(used, 0, sizeof(used));
	memset(pre, -1, sizeof(pre));
	d[s] = 0;
	while (1)
	{
		int v = -1;
		for (int u = 0; u < V; u++)
		{
			if (!used[u] && (v == -1 || d[u] < d[v])) v = u;
		}
		if (v == -1) break;
		used[v] = 1;
		for (int u = 0; u < V; u++)
		{
			if (d[u] > d[v] + cost[v][u])
			{
				d[u] = d[v] + cost[v][u];
				pre[u] = v;
			}
		}
	}
}
vector<int> get_path(int t)
{
	vector<int>path;
	for (; t != -1; t = pre[t]) path.push_back(t);
	reverse(path.begin(), path.end());
	return path;
}

顺便贴一道dij裸体
注意重边,以及输入的先是边再是点
AC代码

#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<stack>
#include<set>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL INF = 0x3f3f3f3f;
LL cost[2010][2010];
LL d[2010];
bool used[2010];
LL V,E;
void dijkstra(LL s)
{
	memset(d, INF, sizeof(d));
	memset(used, 0, sizeof(used));
	d[s] = 0;
	while (1)
	{
		LL v = -1;
		for (LL u = 0; u < V; u++)
		{
			if (!used[u] && (v == -1 || d[u] < d[v])) v = u;
		}
		if (v == -1) break;
		used[v] = 1;
		for (LL u = 0; u < V; u++)
		{
			d[u] = min(d[u], d[v] + cost[v][u]);
		}
	}
}
int main()
{
	IOS;
	cin >> E >> V;
	memset(cost, INF, sizeof(cost));
	for (LL i = 0; i < E; i++)
	{
		LL a, b,w;
		cin >> a >> b>>w;
		cost[a-1][b-1] =cost[b-1][a-1]=min(cost[a-1][b-1],w);
	}
	dijkstra(0);
	cout << d[V-1] << endl;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值