SPFA+链式前向星+SLF优化(最短距离,最短计数,打印多条最短路路径模板)

#include<iostream>
#include<cstring>
#include<deque>
#include<sstream>
#include<vector>
using namespace std;
const int maxn = 1e6 + 7;
const int mode = 100003;  //某模板题 最短路的数量太大,对其其余,
const int INF = 0x3f3f3f;
struct node { int next, v, w; }edge[maxn];
int head[maxn], cnt;
int dis[maxn], counts[maxn], vis[maxn];
int n, m, s, t;
vector<int> pre[maxn];

struct SPFA {
	void init() {
		memset(head, -1, sizeof(head));
		memset(vis, 0, sizeof(vis));
		memset(dis, INF, sizeof(dis));
		memset(counts, 0, sizeof(counts));
		cnt = 0;
	}
	void add(int u, int v, int w) {
		edge[cnt].v = v;    //edge存的是边,不是点!!
		edge[cnt].w = w;
		edge[cnt].next = head[u];
		head[u] = cnt++;
	}
	void print_path(int t, deque<string>cur) {
		cur.push_front(to_string(t));
		if (t == s) {
			while (!cur.empty()) {
				cout << cur.front();
				cur.pop_front();
			}
			cout << endl;
			return;   //结束递归
		}
		else
			cur.push_front("->");
		for (int i = 0; i < pre[t].size(); ++i)
			print_path(pre[t][i], cur);
	}
	void spfa() {
		dis[s] = 0; vis[s] = 1; counts[s] = 1;
		deque<int>q; q.push_front(s);
		while (!q.empty()) {
			int u = q.front(); q.pop_front();
			vis[u] = 0;
			for (int i = head[u]; i != -1; i = edge[i].next) {
				int v = edge[i].v;
				if (dis[v] >= dis[u] + edge[i].w) {
					if (dis[v] > dis[u] + edge[i].w) {
						dis[v] = dis[u] + edge[i].w;
						pre[v].clear();
						pre[v].push_back(u);
						counts[v] = counts[u];
					}
					else {
						pre[v].push_back(u);
						counts[v] += counts[u];
						counts[v] %= mode;
					}
					if (vis[v]) continue;
					vis[v] = 1;
					if (!q.empty() && dis[v] < dis[q.front()])
						q.push_front(v);
					else
						q.push_back(v);
				}
			}
		}
	}
}sp;
int main() {
	while (~scanf("%d%d", &n, &m) && n + m) {
		sp.init();
		int u, v, w;
		while (m--) {
			scanf("%d%d%d", &u, &v, &w);
			sp.add(u, v, w);
			sp.add(v, u, w);    //分清图的类型 有向和无向
		}
		s = 1;
		sp.spfa();
		for (int i = 2; i <= n; i++) {
			printf("%d到%d的最短距离:%d\n", s, i, dis[i]);
			printf("%d到%d的最短路条数:%d ,以下是所有最短路径\n", s, i, counts[i]);
			deque<string>cur;
			sp.print_path(i, cur);
		}
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值