zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    SWT DragSource 和 DropTarget 托拉拽
    Java的反射机制
    1. 算法导论
    SWT对于监听Tab键的理解
    SWT基础
    socket
    TCP/IP
    RPC(远程过程调用协议)
    Jython基本知识
    #与##
  • 原文地址:https://www.cnblogs.com/letlifestop/p/10262904.html
Copyright © 2011-2022 走看看