标签:cnt dist int 短路 SPFA Dijkstra maxn visited counts
题目
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\n", 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\n", counts[i]); }
标签:cnt,dist,int,短路,SPFA,Dijkstra,maxn,visited,counts 来源: https://www.cnblogs.com/Jason66661010/p/12901912.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。