最短路径专题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;
}

最后提交:

相关推荐
Blossom.1184 小时前
移动端部署噩梦终结者:动态稀疏视觉Transformer的量化实战
java·人工智能·python·深度学习·算法·机器学习·transformer
轻微的风格艾丝凡4 小时前
卷积的直观理解
人工智能·深度学习·神经网络·算法·计算机视觉·matlab·cnn
田梓燊6 小时前
红黑树分析 1
算法
晚风吹长发7 小时前
二分查找算法+题目详解
c++·算法·二分查找
悠悠~飘7 小时前
18.PHP基础-递归递推算法
算法·php
pilgrim537 小时前
结合 Leetcode 题探究KMP算法
算法·leetcode
罗义凯8 小时前
其中包含了三种排序算法的注释版本(冒泡排序、选择排序、插入排序),但当前只实现了数组的输入和输出功能。
数据结构·c++·算法
kevien_G18 小时前
JAVA之二叉树
数据结构·算法
syt_biancheng9 小时前
Day3算法训练(简写单词,dd爱框框,3-除2!)
开发语言·c++·算法·贪心算法
二进制的Liao9 小时前
【编程】脚本编写入门:从零到一的自动化之旅
数据库·python·算法·自动化·bash