Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. bool hasCycle(int currNode, vector<vector<pair<int, int>>>& graph, vector<int>& visited) {
  6.     visited[currNode] = 1;
  7.    
  8.     for (auto el : graph[currNode]) {
  9.         if (visited[el.first] == 1) {
  10.             return true;
  11.         }
  12.         else if (visited[el.first] == 0) {
  13.             if(hasCycle(el.first, graph, visited)) {
  14.                 return true;
  15.             }
  16.         }
  17.     }
  18.    
  19.     visited[currNode] = 2;
  20.     return false;
  21. }
  22.  
  23. int main() {
  24.     int n;
  25.     cin >> n;
  26.    
  27.     for (int k = 0; k < n; k++) {
  28.         int size, m;
  29.         cin >> size >> m;
  30.         vector<vector<pair<int, int>>> graph(size + 1);
  31.        
  32.         int x, y, z;
  33.         for (int j = 0; j < m; j++) {
  34.             cin >> x >> y >> z;
  35.            
  36.             graph[x].push_back({y, z});
  37.         }
  38.        
  39.         vector<int> visited;
  40.         visited.assign(size + 1, 0);
  41.        
  42.         bool flag = false;
  43.         for (int i = 1; i <= size; i++) {
  44.             if (visited[i] == 0) {
  45.                 if (hasCycle(i, graph, visited)) {
  46.                     flag = true;
  47.                     break;
  48.                 }
  49.             }
  50.         }
  51.        
  52.         if (flag) {
  53.             cout << "true ";
  54.         }
  55.         else {
  56.             cout << "false ";
  57.         }
  58.     }    
  59.    
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement