原理:若一个点入队的次数超过顶点数V,则存在负环;
1 #include "bits/stdc++.h" 2 3 using namespace std; 4 const int maxN = 200010 ; 5 struct Edge 6 { 7 int to , next , w ; 8 } e[ maxN ]; 9 10 int n,m,cnt,p[ maxN ],Dis[ maxN ]; 11 int In[maxN ]; 12 bool visited[ maxN ]; 13 14 void Add_Edge ( const int x , const int y , const int z ) 15 { 16 e[ ++cnt ] . to = y ; 17 e[ cnt ] . next = p[ x ]; 18 e[ cnt ] . w = z ; 19 p[ x ] = cnt ; 20 return ; 21 } 22 23 bool Spfa(const int S) 24 { 25 int i,t,temp; 26 queue<int> Q; 27 memset ( visited , 0 , sizeof ( visited ) ) ; 28 memset ( Dis , 0x3f , sizeof ( Dis ) ) ; 29 memset ( In , 0 , sizeof ( In ) ) ; 30 31 Q.push ( S ) ; 32 visited [ S ] = true ; 33 Dis [ S ] = 0 ; 34 35 while( !Q.empty ( ) ) 36 { 37 t = Q.front ( ) ;Q.pop ( ) ;visited [ t ] = false ; 38 for( i=p[t] ; i ; i = e[ i ].next ) 39 { 40 temp = e[ i ].to ; 41 if( Dis[ temp ] > Dis[ t ] + e[ i ].w ) 42 { 43 Dis[ temp ] =Dis[ t ] + e[ i ].w ; 44 if( !visited[ temp ] ) 45 { 46 Q.push(temp); 47 visited[temp]=true; 48 if(++In[temp]>n)return false; 49 } 50 } 51 } 52 } 53 return true; 54 } 55 56 int main ( ) 57 { 58 int S , T ; 59 60 scanf ( "%d%d%d%d" , &n , &m , &S , &T ) ; 61 for(int i=1 ; i<=m ; ++i ) 62 { 63 int x , y , _ ; 64 scanf ( "%d%d%d" , &x , &y , &_ ) ; 65 Add_Edge ( x , y , _ ) ; 66 } 67 68 if ( !Spfa ( S ) ) printf ( "FAIL!\n" ) ; 69 else printf ( "%d\n" , Dis[ T ] ) ; 70 71 return 0; 72 }
时间: 2024-12-21 14:44:31