#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;
}
SPFA+链式前向星+SLF优化(最短距离,最短计数,打印多条最短路路径模板)
最新推荐文章于 2024-08-14 17:18:35 发布