poj3259(最短路)
2016-05-04 19:14
435 查看
poj3259 Wormholes
题意:首先输入三个量 N个fields、M个paths、W个wormholes。然后是M行,指 a 和 b 之间的无向边所需花 c 秒。然后是W行,指 a 到 b 所需 -c 秒(这个是有向边)。问你是否存在环?
解决方法:经典的判断负环的题。我用的是Bellman - Ford 算法,就是进行 n - 1 次松弛操作,若进行后仍可以进行松弛操作,就代表有负环,否则负环不存在。
代码实现:
若有错,请大家多多指教^ ^
题意:首先输入三个量 N个fields、M个paths、W个wormholes。然后是M行,指 a 和 b 之间的无向边所需花 c 秒。然后是W行,指 a 到 b 所需 -c 秒(这个是有向边)。问你是否存在环?
解决方法:经典的判断负环的题。我用的是Bellman - Ford 算法,就是进行 n - 1 次松弛操作,若进行后仍可以进行松弛操作,就代表有负环,否则负环不存在。
代码实现:
#include <iostream> #include <algorithm> #include <cstdlib> #include <string> #include <cstring> #include <cstdio> #include <vector> #define Inf 6000000 using namespace std; struct node { int from; int to; int dis; }v[10000]; bool vis[550]; int few[550]; int spfa(int x, int n) { int flag = 0; for(int i = 0; i < n-1; i++) { for(int j = 0; j < x; j++) { if(few[v[j].to] > few[v[j].from] + v[j].dis) { few[v[j].to] = few[v[j].from] + v[j].dis; flag = 1; } } if(!flag) break; } for(int i = 0; i < x; i++) if(few[v[i].to] > few[v[i].from] + v[i].dis) return 0; return 1; } int main() { int T; scanf("%d", &T); while(T--) { int n, m, w; scanf("%d%d%d", &n, &m, &w); int cnt = 0; for(int i = 0; i < n; i++) few[i] = Inf; for(int i = 0; i < m; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); v[cnt].from = a; v[cnt].to = b; v[cnt++].dis = c; v[cnt].from = b; v[cnt].to = a; v[cnt++].dis = c; } for(int i = 0; i < w; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); v[cnt].from = a; v[cnt].to = b; v[cnt++].dis = -c; } memset(vis, false, sizeof(vis)); few[0] = 0; int ans = spfa(cnt, n); if(!ans) printf("YES\n"); else printf("NO\n"); } return 0; }
若有错,请大家多多指教^ ^
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua和C语言的交互详解
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法