最短路 P1144 最短路计数Dijkstra堆优化/SPFA
Posted jason66661010
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最短路 P1144 最短路计数Dijkstra堆优化/SPFA相关的知识,希望对你有一定的参考价值。
题目
https://www.luogu.com.cn/problem/P1144
题目分析
注意相同距离的最短路径条数的判断!(使用数组!)
代码
Dijkstra+堆优化
#include<iostream> #include<cstdio> #include<algorithm> #include<queue> #define maxn 1000002 #define maxm 2000002 #define inf 0x3f3f3f3f using namespace std; struct edge { int to; int next; int dis; }e[maxm]; struct node { int dis; int pos; }; bool operator<(const node &a, const node &b) { return a.dis>b.dis; } int head[maxn], dist[maxn], cnt, visited[maxn],counts[maxn]; int n, m; void addedge(int u, int v, int w) { cnt++; e[cnt].to = v; e[cnt].dis = w; e[cnt].next = head[u]; head[u] = cnt; } priority_queue<node>q; void Dijkstra(int s) { fill(dist, dist + n + 1, inf); dist[s] = 0; counts[s] = 1; q.push({0,s}); while (!q.empty()) { node tmp = q.top(); q.pop(); int x = tmp.pos; if (visited[x])continue; visited[x] = 1; for (int i = head[x]; i; i = e[i].next) { int y = e[i].to; if (dist[y] > dist[x] + e[i].dis) { dist[y] = dist[x] + e[i].dis; counts[y] = counts[x]; q.push({ dist[y], y }); } else if (dist[y] == dist[x] + e[i].dis) { counts[y] += counts[x]; counts[y] %= 100003; } } } } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int a, b; scanf("%d%d", &a, &b); addedge(a, b, 1); addedge(b, a, 1); } Dijkstra(1); for (int i = 1; i <= n; i++) printf("%d ", counts[i]); }
SPFA
#include<iostream> #include<cstdio> #include<algorithm> #include<queue> #define maxn 1000002 #define maxm 2000002 #define inf 0x3f3f3f3f using namespace std; struct edge { int to; int next; int dis; }e[maxm]; int head[maxn], dist[maxn], cnt, visited[maxn], counts[maxn]; int n, m; void addedge(int u, int v, int w) { cnt++; e[cnt].to = v; e[cnt].dis = w; e[cnt].next = head[u]; head[u] = cnt; } queue<int>q; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int a, b; scanf("%d%d", &a, &b); addedge(a, b, 1); addedge(b, a, 1); } fill(dist, dist + n + 1, inf); dist[1] = 0; counts[1] = 1; visited[1] = 1; q.push(1); while (!q.empty()) { int x = q.front(); q.pop(); visited[x] = 0;//这里将visited[x]置为0,防止下面干扰能使路径变短(dist[y] > dist[x] + 1)且不在队列里的节点的判断 for (int i = head[x]; i; i = e[i].next) { int y = e[i].to; if (dist[y] > dist[x] + 1)//能使路径变短(dist[y] > dist[x] + 1)且不在队列里的节点才入队 { dist[y] = dist[x] + 1; counts[y] = counts[x]; if (!visited[y])//节点重复入队是没有意义的!! { q.push(y); visited[y] = 1; } } else if (dist[y] == dist[x] + 1) { counts[y] += counts[x]; counts[y] %= 100003; } } } for (int i = 1; i <= n; i++) printf("%d ", counts[i]); }
以上是关于最短路 P1144 最短路计数Dijkstra堆优化/SPFA的主要内容,如果未能解决你的问题,请参考以下文章