spfa-判断负环
Example
给定一个n个点m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你判断图中是否存在负权回路。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
如果图中存在负权回路,则输出“Yes”,否则输出“No”。
数据范围
1≤n≤20001≤n≤2000,
1≤m≤100001≤m≤10000,
图中涉及边长绝对值均不超过10000。
输入样例:
3 3
1 2 -1
2 3 4
3 1 -4
输出样例:
Yes
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 100010;
int n, m;
int h[N], w[N], e[N], ne[N], idx;
//cnt[N]存边数
int dist[N], cnt[N];//dist[N]狄杰斯特拉的距离,表示从1号点到其他点的最短距离是多少。
bool st[N];//st[]每个点最短路是否确定
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
int spfa()
{
queue<int> q;
//判断是否存在负环,需要把所有点放在队列里面
for (int i = 1; i <= n; i ++)
{
st[i] = true;
q.push(i);//把所有点放进来
}
while (q.size())//while不空
{
int t = q.front();//取队头
q.pop();//删除队头
st[t] = false;//t不在队列
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];//取出当前点
if(dist[j] > dist[t] + w[i])//如果大于就更新
{
dist[j] = dist[t] + w[i];
//更新边
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if (!st[j])//如果j不在队列,才加进去
{
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m --)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);//边和两边距离
add(a, b, c);
}
if (spfa()) puts("Yes");
else puts("No");
return 0;
}