hiho1093_spfa
题目
SPFA模板题,题目中数据可能有两个点之间有多条边直接相连,使用 unordered_map< int, unordered_map< int, int>>, 来存储图的结构,可以方便的去除重边。
实现
#include<stdio.h>
#include<cmath>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<deque>
#include<string>
#include<unordered_map>
#include<unordered_set>
using namespace std; #define max(a, b) (a) > (b)? (a) : (b)
#define min(a, b) (a) < (b)? (a) : (b)
unordered_map<int, unordered_map<int, int>> gMap;
int gMinDist[100005];
bool gInQueue[100005];
int Spfa(int s, int t) {
queue<int> Q;
Q.push(s);
memset(gMinDist, -1, sizeof(gMinDist));
memset(gInQueue, false, sizeof(gInQueue));
gMinDist[s] = 0;
gInQueue[s] = true;
//题目中不存在负权边,因此不需要检查有负权回路。检查存在负权回路,则需要通过
//判断否个点是否被更新超过 N 次,N为点的总数
while (!Q.empty()) {
int u = Q.front();
Q.pop();
gInQueue[u] = false;
for (auto x : gMap[u]) {
int v = x.first;
if (gMinDist[v] == -1 || gMinDist[v] > gMinDist[u] + x.second) {
gMinDist[v] = gMinDist[u] + x.second;
if (!gInQueue[v]) { //如果不存在队列中,则加入队列。剪枝优化
Q.push(v);
}
}
}
}
return gMinDist[t];
}
int main() {
int n, m, s, t;
int u, v, d;
scanf("%d %d %d %d", &n, &m, &s, &t);
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &u, &v, &d); //用 unordered_map 存储图的结构,可以方便的去除重边
if (gMap.find(u) == gMap.end() || (gMap[u].find(v) == gMap[u].end() || gMap[u][v] > d)) {
gMap[u][v] = d;
gMap[v][u] = d;
}
}
int min_dist = Spfa(s, t);
printf("%d\n", min_dist);
return 0;
}
hiho1093_spfa的更多相关文章
随机推荐
- Unix下五种IO模型
http://blog.chinaunix.net/uid-25324849-id-247813.html 1. I/O模型 Unix下共有五种I/O模型 a. 阻塞I/O b. 非阻塞I/O c. ...
- sql中decode(...)函数的用法
相当于if语句 decode函数比较1个参数时 SELECT ID,DECODE(inParam,'beComparedParam','值1' ,'值2') name FROM bank #如果第一个 ...
- java web简单权限管理设计
一套最基本的权限管理包括用户.角色.资源. 数据库设计 我的设计如下: 用户:user 角色:role 用户-角色:user_role 资源:resource(包括上级菜单.子菜单.按钮等资源) 角色 ...
- Codeforces Round #370 (Div. 2) B
Description Memory is performing a walk on the two-dimensional plane, starting at the origin. He is ...
- Educational Codeforces Round 16 B
Description You are given n points on a line with their coordinates xi. Find the point x so the sum ...
- 2016年12月15日 星期四 --出埃及记 Exodus 21:10
2016年12月15日 星期四 --出埃及记 Exodus 21:10 If he marries another woman, he must not deprive the first one o ...
- 2016年11月30日 星期三 --出埃及记 Exodus 20:21
2016年11月30日 星期三 --出埃及记 Exodus 20:21 The people remained at a distance, while Moses approached the th ...
- BZOJ 2433 智能车比赛(计算几何+最短路)
题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=2433 题意:若干个矩形排成一排(同一个x之上最多有一个矩形),矩形i和i+1相邻.给定两 ...
- SQL中添加远程服务器连接
EXEC sp_addlinkedserver 'Testserver','','SQLOLEDB','192.168.1.221' EXEC sp_addlinkedsrvlogin 'Testse ...
- 安装64位版Oracle11gR2后无法启动SQLDeveloper的解决方案
安装64位版Oracle11gR2后发现启动SQL Developer时弹出配置java.exe的路径,找到Oracle自带java.exe后产生的路径“C:\app\用户名\product\11.2 ...