Classic SSSP ( Bellman-Ford )
Note that only negative cycles that are reachable from the source should exert their influence on the other nodes that could be reached from them.
const ll LINF = 1LL << 60; void solve(){ int N, M; cin >> N >> M; vvp G( N ); for( int i = 0; i < M; ++i ){ int u, v, w; cin >> u >> v >> w; G[ u - 1 ].push_back( pii( w, v - 1 ) ); } int st; cin >> st; --st; queue< int > que; vi reachable( N ); reachable[ st ] = 1; que.push( st ); while( not que.empty() ){ int u = que.front(); que.pop(); for( pii e : G[ u ] ) if( not reachable[ e.second ] ) reachable[ e.second ] = 1, que.push( e.second ); } vl dis( N, LINF ); vi no_sp( N ); dis[ st ] = 0; for( int i = 0; i < N; ++i ) for( int j = 0; j < N; ++j ) if( reachable[ j ] ) for( pii e : G[ j ] ) if( upmin( dis[ e.second ], dis[ j ] + e.first ) and i + 1 == N ) no_sp[ e.second ] = 1; for( int i = 0; i < N; ++i ) if( no_sp[ i ] ) que.push( i ); while( not que.empty() ){ int u = que.front(); que.pop(); for( pii e : G[ u ] ) if( upmax( no_sp[ e.second ], 1 ) ) que.push( e.second ); } for( int i = 0; i < N; ++i ){ if( reachable[ i ] and no_sp[ i ] ) cout << "-oo\n"; else if( not reachable[ i ] ) cout << "oo\n"; else cout << dis[ i ] << "\n"; } }