poj3259:spfa解法
2015-10-09 16:36
393 查看
构建一个队列,将松弛成功且不在队列的点放入队列,每次出队一个点.直到队列为空,如果队列中的某个入队次数超过n次,就说明存在一个负环.
#include "vector" #include "queue" #include "iostream" using namespace std; const double inf = 10000000; struct node { int end; double time_cost; }; typedef vector<double> D; bool relax(int beg,int end,double cost, D &distance) { if (distance[beg] + cost < distance[end]) { distance[end] = distance[beg] + cost; return true; } return false; } bool spfa(int N,D&distance, vector<vector<node>>& head) { queue<int> Q; vector<int> isinq(N+1, 0); vector<int> visited(N + 1, 0); distance[0] = 0; Q.push(0); isinq[0] = 1; while (!Q.empty()) { int beg = Q.front(); Q.pop(); isinq[beg] = 0;//不在队列中 for (auto it : head[beg]) { if (relax(beg, it.end, it.time_cost, distance)) { if (!isinq[it.end]) { Q.push(it.end); isinq[it.end] = 1; if (++visited[it.end] > N) return true; } } } } return false; } int main() { int F, N, M, W; cin >> F; while (F--) { cin >> N >> M >> W; vector<vector<node>> head(N + 1);//N+1个点 int S, E; double T; while (M--)//普通path { cin >> S >> E >> T; head[S].push_back({ E, T }); head[E].push_back({ S, T }); } while (W--)//虫洞 one_way { cin >> S >> E >> T; head[S].push_back({ E, -T }); } int count = N; while (count--) head[0].push_back({count+1,0}); //初始化 auto it = head.begin(); bool ispossible = false; D distance(N+1,inf); ispossible = spfa(N,distance,head); if (ispossible) cout << "YES" << endl; else cout << "NO"<<endl; } return 0; }
相关文章推荐
- grail安装和创建一个简单的例子
- libxml2编程--C语言xml初使用(1)
- libxml2编程--C语言xml初使用(1)
- libxml2编程--C语言xml初使用(1)
- 把启动脚本设置成开机自启动
- webstorm快捷键
- hihoCoder 1233 Boxes 哈希+最短路
- ssh add new key
- 自助终端机上a标签的兼容性
- Python 远程桌面协议RDPY简介
- 什么是Nib文件?(Nib文件是一种特殊类型的资源文件,它用于保存iPhone OS或Mac OS X应用程序的用户接口)
- 关于Programming Collective Intelligence中使用pydelicious.py的若干问题
- 蓝牙基本流程
- 找了个上传文件的html
- Algorithms—278.First Bad Version
- 【Cocos2dx】精灵触摸跳跃功能
- C#中object missing = Type.Missing是什么意思
- 支付宝接口开发总结
- 阿里云云服务器硬盘分区及挂载
- EntityFramework 外键值映射