dalao求助,全re
查看原帖
dalao求助,全re
879396
zzf12345666楼主2023/3/21 00:27
import java.util.*;
 public class Main {
 static int N = 3100;
 static int n,m,t,idx;
 static int[] h = new int[N], e = new int[N], ne = new int[N], w = new int[N];
 static int[] dist = new int[N], count = new int[N];
   static boolean[] st = new boolean[N];
    static void main(String[] args) 
    {
       Scanner in = new Scanner(System.in);
        t=in.nextInt();
        while(t-->0){  
        n = in.nextInt(); m = in.nextInt();
        Arrays.fill(h, -1);
        Arrays.fill(e, 0);
        Arrays.fill(ne, 0);
        Arrays.fill(w, 0);
        while (m-- > 0) 
        {
          int x = in.nextInt();
          int y = in.nextInt(); 
          int c = in.nextInt();
          add(x, y, c);
         }
     if (spfa()) System.out.println("Yes");
       else System.out.println("No");
       }
   }
     public static void add (int x, int y, int c){
        e[idx] = y;
        w[idx] = c;
        ne[idx] = h[x];
        h[x] = idx++;
    }

   public static boolean spfa() 
    {
    Queue<Integer> q = new LinkedList<>();
        for (int i = 1; i<=n; i++) 
        {
            st[i] = true;
            q.add(i);
        }
        while (q.size() > 0)
        {
            int t = q.poll();
            st[t] = false;
      for (int i = h[t]; i!=-1; i = ne[i]) 
      {
         int j = e[i];
         if (dist[j] > dist[t] + w[i]) 
         {
           dist[j] = dist[t] + w[i];
           count[j] = count[t] + 1;
           if(count[j] >= n) return true;
            if (!st[j]) 
            {
               q.add(j);
               st[j] = true;  
             }
           }
        }
     }
      return false;
  }
}
2023/3/21 00:27
加载中...