spfa判断负权回路(负环)

小技巧:如果使用队列实现SPFA判负环超时了,可以尝试使用栈来实现,很多情况下会比队列要快一些。

#include<bits/stdc++.h>
using namespace std;

const int N = 2e3 + 100;
const int M = 1e5 + 100;

int h[N], dis[N], cnt[N], w[M], st[N], e[M], ne[M], idx;
int n, m;

void add(int a, int b, int c)
{
    w[idx] = c;
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}


bool spfa()
{
    queue<int>Q;
    for(int i = 1; i <= n; i ++)
        Q.push(i), st[i] = 1;
	
	int count = 0;
    while(Q.size())
    {
        int head = Q.front();
        Q.pop();
        st[head] = 0;
        
        for(int j = h[head]; ~j; j = ne[j])
        {
            int x = e[j];
            if(dis[x] > dis[head] + w[j])
            {
                dis[x] = dis[head] + w[j];
                cnt[x] = cnt[head] + 1;//记录最短路径的边数 
				if(++ count >= 10000) return true; //如果spfa的运行次数很多,我们可以近似的认为存在负环(经验性trick)
				//这个东西如果原代码没超时的话尽量不要写,否则有可能会导致原图无负环,判成了负环
                if(cnt[x] >= n) return true;//最短路径边数>=n,即存在被重复遍历的点,也就是存在负环
                if(st[x] == 0)
                {
                    Q.push(x);
                    st[x] = 1;
                }
            }
        }
    }
    return false;
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    for(int i = 0; i < m; i ++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    
    if(spfa()) puts("Yes");
    else puts("No");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值