最短路径专题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 值,就是累计路径条数。

代码详解如下:

#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;
}

最后提交:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值