852. spfa判斷負環

給定一個n個點m條邊的有向圖,圖中可能存在重邊和自環, 邊權可能爲負數。java

請你判斷圖中是否存在負權迴路。nginx

輸入格式

第一行包含整數n和m。spa

接下來m行每行包含三個整數x,y,z,表示存在一條從點x到點y的有向邊,邊長爲z。code

輸出格式

若是圖中存在負權迴路,則輸出「Yes」,不然輸出「No」。xml

數據範圍

1n2000
1m10000
圖中涉及邊長絕對值均不超過10000。
blog

輸入樣例:

3 3
1 2 -1
2 3 4
3 1 -4

輸出樣例:

Yes

代碼:
//鄰接表存儲
//n=1e5,不能用鄰接表

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class Main{
        static final int N=100005, INF=0x3f3f3f3f;
        static int h[]=new int[N];
        static int e[]=new int[N];
        static int ne[]=new int[N];
        static int w[]=new int[N];
        static int dis[]=new int[N];
        static int cnt[]=new int[N];//
        static boolean vis[]=new boolean[N];
        static int n,m,idx;
        static void add(int a,int b,int c){
                e[idx]=b;
                w[idx]=c;
                ne[idx]=h[a];
                h[a]=idx++;
        }
        static boolean spfa(){
                ArrayDeque<Integer> q = new ArrayDeque<Integer>();
                Arrays.fill(dis, INF);
                dis[1]=0;
                for(int i=1;i<=n;i++){//不能只加入1了,由於每一個點都要判斷一下,負權迴路並非每一個點都能進入的
                    q.offer(i);
                    vis[i]=true;
                }
                while(!q.isEmpty()){
                        int t=q.poll();
                        vis[t]=false;//不在隊列中,置爲false
                        for(int i=h[t];i!=-1;i=ne[i]){
                                int j=e[i];
                                if(dis[j]>dis[t]+w[i]){
                                        dis[j]=dis[t]+w[i];
                                        cnt[j]=cnt[t]+1;
                                        if(cnt[j]>=n) return true;//若是存在負權迴路,路徑那麼會一直執行更新,就是在這個負環中轉圈;對圖中的點,它最多通過n-1條邊到達另外一個點,因此大於等於n,確定是存在負權迴路
                                        if(!vis[j]){
                                                vis[j]=true;
                                                q.offer(j);
                                        }
                                }
                        }
                }
                return false;
        }
        public static void main(String[] args) {
                Scanner scan=new Scanner(System.in);
                n=scan.nextInt();
                m=scan.nextInt();
                Arrays.fill(h, -1);
                while(m-->0){
                        int a=scan.nextInt();
                        int b=scan.nextInt();
                        int c=scan.nextInt();
                        add(a,b,c);
                }
                if(spfa()) System.out.println("Yes");
                else System.out.println("No");
        }
}
相關文章
相關標籤/搜索