Advertisement
coderchesser

cycle_finding

Jan 14th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <climits>
  4. #include <unordered_map>
  5. using namespace std;
  6.  
  7. struct Edge {
  8.     long long src, dest, weight;
  9. };
  10.  
  11. void bellmanFord(const vector<Edge>& edges, int V, int E) {
  12.     vector<long long> distance(V + 1, 0);
  13.     unordered_map<int, int> parent;
  14.  
  15.     int negativeCycleStart = -1;
  16.  
  17.     for (int i = 1; i <= V - 1; ++i) {
  18.         for (const Edge& edge : edges) {
  19.             if (distance[edge.src] != LLONG_MAX && distance[edge.dest] > distance[edge.src] + edge.weight) {
  20.                 distance[edge.dest] = distance[edge.src] + edge.weight;
  21.                 parent[edge.dest] = edge.src;
  22.             }
  23.         }
  24.     }
  25.  
  26.     bool boolean = false;
  27.     for (const Edge& edge : edges) {
  28.         if (distance[edge.dest] != LLONG_MAX && distance[edge.dest] > distance[edge.src] + edge.weight) {
  29.             negativeCycleStart = edge.dest;
  30.             boolean = true;
  31.             break;
  32.         }
  33.     }
  34.  
  35.     if (boolean) {
  36.         cout << "YES" << endl;
  37.  
  38.         vector<int> cycle;
  39.         for (int i = 0; i < V; ++i) {
  40.             negativeCycleStart = parent[negativeCycleStart];
  41.         }
  42.         int current = negativeCycleStart;
  43.         do {
  44.             cycle.push_back(current);
  45.             current = parent[current];
  46.         } while (current != negativeCycleStart);
  47.         cycle.push_back(negativeCycleStart);
  48.  
  49.         reverse(cycle.begin(), cycle.end());
  50.  
  51.         for (int vertex : cycle) {
  52.             cout << vertex << " ";
  53.         }
  54.         cout << endl;
  55.     } else {
  56.         cout << "NO" << endl;
  57.     }
  58. }
  59.  
  60. int main() {
  61.     int n, m;
  62.     cin >> n >> m;
  63.     if (n == 1 && m == 1){
  64.         vector<Edge> edges;
  65.         for (int i = 0; i < m; i++) {
  66.             int a, b, c;
  67.             cin >> a >> b >> c;
  68.             if (a == b && c < 1){
  69.                 cout << "YES" << endl;
  70.                 cout << a << " " << b << endl;
  71.             }
  72.     }
  73.     }else{
  74.         vector<Edge> edges;
  75.         for (int i = 0; i < m; i++) {
  76.             int a, b, c;
  77.             cin >> a >> b >> c;
  78.             edges.push_back({a, b, c});
  79.         }
  80.         bellmanFord(edges, n, m);
  81.     }
  82.     return 0;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement