Loop negative determination AcWing 852. spfa

#include <CString> 
#include <the iostream> 
#include <algorithm> 
#include <Queue>
 the using  namespace STD;
 const  int N = 2010 , M = 10010 ;
 int n-, m;
 int H [N], W [M], E [M], NE [M], IDX;
 int dist [N]; // shortest distance 
int CNT [N]; // number of edges in the most short-circuited, if more than equal to n, then there is a negative ring 
BOOL ST [N ];
 void the Add ( int A, int B, int C) { 
    E [IDX] = B, W [IDX] = C, NE [IDX] = H [A], H [A] = IDX ++; 
} 
Int SPFA () { 
    Queue < int > Q;
     for ( int I = 1 ; I <= n-; I ++ ) { 
        ST [I] = to true ; // may not negative to a ring, then put all points added to the list 
        q.push (I); 
    } 
    the while (q.size ()) {
         int T = q.front (); 
        q.pop (); 
        ST [T] = to 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];
                cnt[j] = cnt[t] + 1;
                if (cnt[j] >= n) return true;
                if (!st[j]) {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }
    return false;
}
int main() {
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    while (m -- ) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    if (spfa()) puts("Yes");
    else puts("No");
    return 0;
}

 

 

 

Guess you like

Origin www.cnblogs.com/QingyuYYYYY/p/11842171.html