最短路径专题4 最短路径条数

题目:

样例:

|---------------------------------------|
| 4 5 0 2 0 1 2 0 2 5 0 3 1 1 2 1 3 2 2 |
[输入]

|-----|
| 3 2 |
[输出]

思路:

同样的求最短距离即可,不同的是,我们要记录好路径条数,用 path 数组存储每个结点的路径条数,走动的下一个结点,继承上一个结点的 path 数值,当出现最短的距离相同时,累加该结点的 path 值,就是累计路径条数。

代码详解如下:

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
#define endl '\n'
#define x first
#define y second
#define mk make_pair
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define INF 0x3f3f3f3f3f3f3f
#define All(x) (x).begin(),(x).end()
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;
using PII = pair<int,int>;
int n,m,start,last;

int dist[N];	// 记录最短距离
bool st[N];		// 标记每一个结点是否走动过
int path[N];	// 记录每个结点的路径条数

// 建立链表
int h[N],e[N],w[N],ne[N],idx;
inline void Add(int a,int b,int c)
{
	e[idx] = b,w[idx] = c,ne[idx] = h[a],h[a] = idx++;
}

inline void Dijkstra()
{
	// 初始化最短距离
	memset(dist,INF,sizeof dist);
	dist[start] = 0;
	
	// 默认起点开始的路径条数是 1
	path[start] = 1;
	
	// 建立堆,默认 first 从小到大排序
	priority_queue<PII,vector<PII>,greater<PII>>q;

	// 存储起点以及最短距离关系
	q.push(mk(0,start));
	
	// 开始堆排序的 Dijkstra
	while(q.size())
	{
		// 获取当前结点与最短距离的对组
		PII now = q.top();
		q.pop();
		
		int a = now.y;// 获取当前结点
		int dis = now.x;// 获取当前结点对应的最短距离
		
		// 如果当前结点走动过,不必更新最短距离
		if(st[a]) continue;
		st[a] = true;	// 标记当前走动的结点
		
		// 遍历链表,更新当前结点对应的各个节点的最短距离
		for(int i = h[a];i != -1;i = ne[i])
		{
			int j = e[i];	// 获取下一个的结点
			
			// 如果当前 j 结点的最短距离方案比 , a 结点 到 j 结点的距离还大
			if(dist[j] > dis + w[i])
			{
				// 更新最短距离
				dist[j] = dis + w[i];
				
				// 由于是更新最短距离,所以继承 a 结点的路径条数
				path[j] = path[a];
			}else // 否则如果出现最短距离方案相同,那么累计路径条数,即累加 a 结点的路径条数
			if(dist[j] == dis + w[i]) path[j] += path[a];
			
			// 存储当前结点和相应的最短距离关系对组,方便下一次的走动
			q.push(mk(dist[j],j));
		}
	}
	return ;
}

inline void solve()
{
	// 初始化链表
	memset(h,-1,sizeof h);
	
	cin >> n >> m >> start >> last;
	
	while(m--)
	{
		int a,b,c;
		cin >> a >> b >> c;
		
		// 由于是无向图,所以添加两个结点的链表
		Add(a,b,c);
		Add(b,a,c);
	}
	// 开始 Dijkstra 求值
	Dijkstra();
	
	// 输出终点最短路距离和路径条数
	cout << dist[last] << ' ' << path[last] << endl;
}

signed main()
{
//	freopen("a.txt", "r", stdin);
	___G;
	int _t = 1;
//	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

最后提交:

相关推荐
尼尔森系4 小时前
排序与算法:希尔排序
c语言·算法·排序算法
AC使者4 小时前
A. C05.L08.贪心算法入门
算法·贪心算法
冠位观测者4 小时前
【Leetcode 每日一题】624. 数组列表中的最大距离
数据结构·算法·leetcode
yadanuof5 小时前
leetcode hot100 滑动窗口&子串
算法·leetcode
可爱de艺艺5 小时前
Go入门之函数
算法
武乐乐~5 小时前
欢乐力扣:旋转图像
算法·leetcode·职场和发展
a_j585 小时前
算法与数据结构(子集)
数据结构·算法·leetcode
清水加冰6 小时前
【算法精练】背包问题(01背包问题)
c++·算法
慢一点会很快8 小时前
FRRouting配置与OSPF介绍,配置,命令,bfd算法:
算法·智能路由器·php·ospf
88号技师9 小时前
2024年中科院一区SCI-雪雁优化算法Snow Geese Algorithm-附Matlab免费代码
开发语言·人工智能·算法·matlab·优化算法