J - Invitation Cards——最短路_spfa()算法
2017-07-20 16:34
260 查看
Think:
1知识点:最短路_spfa()算法+前向星
2反思:
1>函数中形参和实参的传递,数组传进的为地址,形参改变实参相应的改变,而传进的标记变量形参改变实参不改变
2>遇到bug要精心debug
vjudge题目链接
建议参考博客链接
以下为Accepted代码
1知识点:最短路_spfa()算法+前向星
2反思:
1>函数中形参和实参的传递,数组传进的为地址,形参改变实参相应的改变,而传进的标记变量形参改变实参不改变
2>遇到bug要精心debug
vjudge题目链接
建议参考博客链接
以下为Accepted代码
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int inf = 0x3f3f3f3f; const int N = 1e6 + 4; const int M = 1e6 + 4; struct Edge{ int v; int w; int next; }e1[M*2], e2[M*2]; int n, m, cnt1, cnt2, head1 , head2 , dis , vis ; int add_edge(int u, int v, int w, struct Edge e[M*2], int head , int cnt); void spfa(int x, struct Edge e[M*2], int head ); int main(){ int T, i, u, v, w; long long sum; scanf("%d", &T); while(T--){ scanf("%d %d", &n, &m); sum = 0, cnt1 = cnt2 = 0; memset(head1, -1, sizeof(head1)); memset(head2, -1, sizeof(head2)); for(i = 1; i <= m; i++){ scanf("%d %d %d", &u, &v, &w); cnt1 = add_edge(u, v, w, e1, head1, cnt1); cnt2 = add_edge(v, u, w, e2, head2, cnt2); } spfa(1, e1, head1); for(i = 1; i <= n; i++){ sum += dis[i]; } spfa(1, e2, head2); for(i = 1; i <= n; i++){ sum += dis[i]; } printf("%lld\n", sum); } return 0; } int add_edge(int u, int v, int w, struct Edge e[M*2], int head , int cnt){ e[cnt].v = v; e[cnt].w = w; e[cnt].next = head[u]; head[u] = cnt++; return cnt; } void spfa(int x, struct Edge e[M*2], int head ){ queue <int> q; while(!q.empty()){ q.pop(); } memset(dis, inf, sizeof(dis)); memset(vis, 0, sizeof(vis)); dis[x] = 0, vis[x] = 1; q.push(x); while(!q.empty()){ int t1 = q.front(); q.pop(); vis[t1] = 0; for(int i = head[t1]; ~i; i = e[i].next){ if(dis[t1] + e[i].w < dis[e[i].v]){ dis[e[i].v] = dis[t1] + e[i].w; if(!vis[e[i].v]){ vis[e[i].v] = 1; q.push(e[i].v); } } } } }
相关文章推荐
- 【打CF,学算法——三星级】CodeForces 689B Mike and Shortcuts (最短路+spfa)
- 蓝桥杯算法练习最短路(spfa)
- 最短路 spfa 算法 && 链式前向星存图
- 带权最短路 Dijkstra, SPFA, Bellman-Ford, ASP, Floyd-Warshall 算法分析
- 算法训练 最短路 spfa
- N - Tram——最短路_spfa()算法
- O - Extended Traffic——最短路_spfa()算法+前向星+判断负环
- 蓝桥杯 - 算法训练 最短路(spfa)
- 算法训练 最短路 spfa
- 【算法系列学习】SPFA邻接表最短路 [kuangbin带你飞]专题四 最短路练习 F - Wormholes
- 蓝桥杯 算法训练 最短路 spfa
- 带权最短路 Dijkstra, SPFA, Bellman-Ford, ASP, Floyd-Warshall 算法分析
- G - MPI Maelstrom——最短路_spfa()算法
- spfa 算法 (单源最短路)
- 最短路(SPFA)算法
- Bellman变形得来的SPFA最短算法(不能含负环);Floyd求两点间最短路,求有向图的闭包;
- 【DayDayUp】【算法_图_最短路_之二_SPFA最劣、Dij堆优化&Johnson(结点对最短路)】(待续)
- 【最短路三算法】Floyd,Dijkstra,SPFA.
- 蓝桥杯 - 算法训练 - ALGO - 5 最短路(spfa)
- S - Layout ——最短路_spfa()算法+前向星+负环+差分约束