zoukankan      html  css  js  c++  java
  • 用spfa 判负环

    #include<stdio.h>
    #include<cstring>
    #include<queue>
    #include<algorithm>
    using namespace std;

    struct my{
      int v;
      int next;
      int dist;
    };

    int m,n;
    const int maxn=100000;
    my bian[maxn];
    int adj[maxn];
    int fa;
    bool vis[maxn];
    int d[maxn];
    int cnt[maxn];

    void myinsert(int u,int v,int zhi){
        bian[++fa].v=v;
        bian[fa].dist=zhi;
        bian[fa].next=adj[u];
        adj[u]=fa;
    }

    bool spfa(){
         queue<int>q;
         for (int i=1;i<=n;i++){
            q.push(i);
            d[i]=0;
         }
         vis[1]=true;
         while(!q.empty()){
            int u=q.front();
                q.pop();
                vis[u]=false;
            for (int i=adj[u];i!=-1;i=bian[i].next){
                if(d[bian[i].v]>d[u]+bian[i].dist){
                    d[bian[i].v]=d[u]+bian[i].dist;
                    if(!vis[bian[i].v]){
                        q.push(bian[i].v);
                        vis[bian[i].v]=true;
                        if(++cnt[bian[i].v]>n) return true;
                    }
                }
            }
         }
        return false;
    }
    int main(){
        memset(bian,-1,sizeof(bian));
        memset(adj,-1,sizeof(adj));
       scanf("%d%d",&n,&m);
       int u,v,zhi;
       for (int i=1;i<=m;i++){
        scanf("%d%d%d",&u,&v,&zhi);
        myinsert(u,v,zhi);
        myinsert(v,u,zhi);
       }
      if( spfa()) printf("yes ");
      else printf("no ");

    return 0;
    }

  • 相关阅读:
    存储过程
    输入http://localhost/,apache出现You don't have permission to access/on this server.的提示,如何解决?
    搭建内网的NTP时间服务器
    cobbler自动化安装系统
    Linux三剑客之awk最佳实践
    ansible学习笔记
    2021.05.07 多线程之可重入锁
    2021.05.08 easyExcel简单读写
    2021.05.03 Java常用文件路径
    2021.05.04 二维码生成与解析
  • 原文地址:https://www.cnblogs.com/lmjer/p/8330483.html
Copyright © 2011-2022 走看看