如题,求单源单汇最短路径
SPFA和Dijkstra朴素/堆优化见https://blog.csdn.net/qq_35850147/article/details/88533218
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
const int maxm = 2e5 + 10;
bool vis[maxn];
int cnt, top, head[maxn], dis[maxn], pre[maxn], sta[maxn]; // cnt为边计数,top为答案路径栈顶,head[i]为该顶点的边集首下标,dis[i]缓存松弛过程中s到i的距离,pre[]保存答案路径前驱,sta[]保存答案路径
string place[maxn]; // 保存地点名称
struct edge { int v, w, next; } e[maxm]; // 链式前向星存图
struct node
{
int u, w;
bool operator < (const node &n) const { return w > n.w; }
};
priority_queue<node> q; // Dijkstra堆优化
inline const int read()
{
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
return x * f;
}
void addEdge(int u, int v, int w)
{
e[cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt++;
}
void dijkstra(int src)
{
memset(dis, 0x3f, sizeof(dis));
dis[src] = 0;
q.push(node{src, 0});
while (!q.empty())
{
int u = q.top().u; q.pop();
if (vis[u]) continue;
vis[u] = true;
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].v, w = e[i].w;
if (dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
pre[v] = u;
q.push(node{v, dis[v]});
}
}
}
}
int main()
{
printf("请分别输入地点总数、直达路径总数:");
int n = read(), m = read();
for (int i = 1; i <= n; i++)
{
printf("请输入第%d个地点的名称:", i);
scanf("%s", &place[i][0]);
}
memset(head, -1, sizeof(head));
for (int i = 1; i <= m; i++)
{
printf("请分别输入第%d条直达路径的两端点编号和长度:", i);
int u = read(), v = read(), w = read();
addEdge(u, v, w);
addEdge(v, u, w);
}
printf("请输入源点编号和终点编号:");
int s = read(), t = read();
dijkstra(s);
for (int i = t; i != s; i = pre[i]) sta[top++] = i;
for (int i = top - 1, last = s; i >= 0; i--)
{
int u = last, v = sta[i];
printf("从%d: %s 到%d: %s\n", u, place[u].c_str(), v, place[v].c_str());
last = v;
}
printf("总路程为:%d\n", dis[t]);
return 0;
}