bellman-ford算法(判断有没有负环)

#include <iostream>
#include <vector>
#include<string>
#include<cstring>
using namespace std;
# define ll long long
# define maxn 1000+10
# define inf 0x3f3f3f3f
int n,m,t;
double mg;
struct node
{
    int to;
    double lv;
    double  yon;
    node(int w,double t1,double t2)
    {
        to=w;
        lv=t1;
        yon=t2;
    }
};
vector<node>wakaka[maxn];
double  dis[maxn];
bool spfa()
{
    for(int i=1; i<=n; i++)dis[i]=0;
    dis[t]=mg;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
        {
            int len=wakaka[j].size();
            for(int k=0; k<len; k++)
            {
                node temp=wakaka[j][k];
                if((dis[j]-temp.yon)*temp.lv>dis[temp.to])
                {
                    dis[temp.to]=(dis[j]-temp.yon)*temp.lv;
                    if(i==n)return true;
                }
            }
        }
    }
    return false;

    for(int i=1; i<=n; i++)//判断负环
    {
        if(dis[q[i].to]>dis[i]+wakaka[q[i]].cost)
            break;
    }
}
int main()
{
    while(cin>>n>>m>>t>>mg)
    {
        for(int i=1; i<=n; i++)
        {
            wakaka[i].clear();
        }
        for(int i=1; i<=m; i++)
        {
            int t1,t2;
            double s1,s2,w1,w2;
            cin>>t1>>t2>>s1>>w1>>s2>>w2;
            wakaka[t1].push_back(node(t2,s1,w1));
            wakaka[t2].push_back(node(t1,s2,w2));
        }
        if(spfa())cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
    return 0;
}

 

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/Let_life_stop/article/details/82790675
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞