bellman 判断负环 acwing 852

虽然是SPFA 判断负环比较省时,但是我感觉bellman算法思路更加简单呐。


#include <iostream>// bellman
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 10010;

int bis[N], n, m;

struct E
{
    int a, b, c; 
}edgs[N];

bool bellman()
{
    memset(bis, 0x3f, sizeof bis);
    bis[1] = 0;
    for(int i = 0; i < n ; i ++)
    {
        for(int j = 0; j < m ; j ++)
        {
            int as = edgs[j].a, bs = edgs[j].b, c = edgs[j].c;
            bis[bs] = min(bis[bs], bis[as] + c);
        }
    }
    for(int i = 0; i < m ; i ++)
    {
        int as = edgs[i].a, bs = edgs[i].b, c = edgs[i].c;
        if(bis[bs] > bis[as] + c) return false;
    }
   
    return true;
}

int  main()
{
    cin >> n >> m;
    for(int i = 0; i < m; i ++) 
    {
        int a, b, c;
        scanf("%d %d %d", &a, &b, &c);
        edgs[i] = {a, b, c};
    }
    if(bellman()) cout << "No" << endl;
    else cout << "Yes" << endl;
}
#include<iostream>// SPFA
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;

const int N = 2010, M = 10010;

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


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

bool SPFA()
{
    queue <int> q; 
    for(int i = 1; i <= n ; i ++)q.push(i);
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        for(int i = h[t]; i != -1; i = ne[i])
        {
            int a = e[i], wd = w[i];
            if(bis[a] > bis[t] + wd)
            {
                bis[a] = bis[t] + wd;
                cnt[a] = cnt[t] + 1;
                if(cnt[a] > n - 1) return true;
                q.push(a);
            }
        }
    }
    return false;
}
int main()
{
    memset(h , -1, sizeof h);
    cin >> n >> m;
    for(int i = 0; i < m ; i ++)
    {
        int a, b, c;
        scanf("%d %d %d",&a, &b, &c);
        add(a, b, c);
    }
    if(SPFA() == false) puts("No");
    else puts("Yes");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值