Advertisement
tepyotin2

Negative Cycle Detection

May 21st, 2025
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Edge{
  6.     int from, to, weight;
  7. };
  8.  
  9. int t;
  10. int n, m;
  11. vector<Edge> graph;
  12.  
  13. bool isNegative(){
  14.     vector<int> dist;
  15.     dist.resize(n+1, 0);
  16.     dist[1] = 0;
  17.     bool check = false;
  18.     for(int i=1; i<=n; i++){
  19.         check = false;
  20.         for(Edge e: graph){
  21.             if(dist[e.from] != INT_MAX){
  22.                 if(dist[e.to]>dist[e.from]+e.weight){
  23.                     //cout << "HI" << '\n';
  24.                     dist[e.to] = dist[e.from]+e.weight;
  25.                     //cout << "i: " << i << ", dist[e.to]: " << dist[e.to] << ", dist[e.from]: " << dist[e.from] << '\n';
  26.                     check = true;
  27.                     if(i==n){
  28.                         return true;
  29.                     }
  30.                 }
  31.             }
  32.         }
  33.         if(!check) break;
  34.     }
  35.     return false;
  36. }
  37.  
  38. int main(){
  39.     //freopen("negativecycle.in", "r", stdin);
  40.    
  41.     cin >> t;
  42.     while(t--){
  43.         cin >> n >> m;
  44.         graph.clear();
  45.         graph.resize(m);
  46.         //dist.resize(n+1, INT_MAX);
  47.         for(int i=0; i<m; i++){
  48.             cin >> graph[i].from >> graph[i].to >> graph[i].weight;
  49.             //cout << graph[i].from << ", " << graph[i].to << ", " << graph[i].weight << '\n';
  50.         }
  51.         if(isNegative()){
  52.             cout << "YES" << '\n';
  53.         }else{
  54.             cout << "NO" << '\n';
  55.         }
  56.     }
  57.    
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement