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;
}

 

posted @ 2018-09-20 17:12  Let_Life_Stop  阅读(153)  评论(0编辑  收藏  举报