poj 3259 wormholes AC代码(负权环判断, Bellmanford)
2015-06-17 14:34
267 查看
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> #include<iomanip> #include<cstdlib> #include<cstdio> #include<vector> #include<algorithm> #include<cmath> #include<map> using namespace std; const int INF = 10001; struct Edge { int from; int to; int wgt; Edge(int f = -1, int t = -1, int w = INF) : from(f), to(t), wgt(w){} }; bool bellmanford(vector<Edge> &G, int num, int src) { vector<int> dist(num+1, INF); dist[src] = 0; int st; for (st = 0; st < num; ++st) { bool chg = false; for (int i = 0; i < G.size(); ++i) { if (dist[G[i].to] > dist[G[i].from] + G[i].wgt) { dist[G[i].to] = dist[G[i].from] + G[i].wgt; chg = true; } } if (!chg) break; } if (st == num) return true; else return false; } int main(void) { int F; cin >> F; while (F--) { int N, M, W; cin >> N >> M >> W; vector<Edge> G; for (int i = 0; i < M; ++i) { int s, e, t; scanf("%d%d%d", &s, &e, &t); G.push_back(Edge(s, e, t)); G.push_back(Edge(e, s, t)); } for (int i = 0; i < W; ++i) { int s, e, t; scanf("%d%d%d", &s, &e, &t); G.push_back(Edge(s, e, -t)); } if (bellmanford(G, N, 1)) cout << "YES" << endl; else cout << "NO" << endl; } //system("pause"); return 0; }
如果用STL做邻接矩阵的话会超时,内存申请释放开销太大.而且题目中<span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">N</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> (1 ≤ </span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">N</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> ≤ 500), <span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">M</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> (1 ≤ </span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">M</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> ≤ 2500), <span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">W</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> (1 ≤ </span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">W</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> ≤ 200) 明显为稀疏图,如果用邻接矩阵表示的话,搜索的开销也会很大.于是考虑储存边的信息.</span></span></span>
相关文章推荐
- c#常见stream操作
- 在ubuntu下添加字典 GoldenDict
- java控制台版扫雷
- java String类有关静态变量,常量池,引用对象的问题
- QTableWidget 列排序
- asp.net 初级入门学习之ATM
- 收藏:c语言的多线程同步
- java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] 不能使用 '(未知的)';文件已在使用中
- Java NIO系列教程(十一) Pipe
- mtk 驱动笔记 lcd camera led tp
- 二,mogodb索引
- Python的数据格式动态标记格式
- github生成个公钥
- Go视频教程整理
- C语言sscanf的用法总汇
- Struts2框架实现简单的用户登入
- PHP高效率写法
- 编程随记
- java对象的强引用,软引用,弱引用和虚引用
- PHP中比较两个时间的大小与日期的差值