D_L3

test 6 - 2022-2023 - Цикличен граф

Jan 8th, 2024
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <unordered_map>
  7.  
  8. using namespace std;
  9.  
  10. bool hasCycle(unordered_map<int, vector<int>>& graph, vector<bool>& visited, vector<bool> pathVisited, int idx) {
  11.     if(pathVisited[idx])
  12.         return true;
  13.     pathVisited[idx] = true;
  14.     for(auto neighbour : graph[idx]){
  15.         if(hasCycle(graph, visited, pathVisited, neighbour))
  16.             return true;
  17.     }
  18.     pathVisited[idx] = false;
  19.     visited[idx] = true;
  20.     return false;
  21.    
  22. }
  23.  
  24. bool test(){
  25.     int v, e, x, y, w;
  26.     cin >> v >> e;
  27.     unordered_map<int, vector<int>> graph;
  28.     for(int i = 0; i < e; i++){
  29.         cin >> x >> y >> w;
  30.         graph[x - 1].push_back(y - 1);
  31.     }
  32.     vector<bool> visited(v, false);
  33.    
  34.     for(int i = 0; i < v; i++) {
  35.         if(!visited[i]){
  36.             vector<bool> pathVisited(v, false);
  37.             if(hasCycle(graph, visited, pathVisited, i)){
  38.                 return true;
  39.             }
  40.         }
  41.     }
  42.     return false;
  43. }
  44.  
  45.  
  46. int main() {
  47.     int n;
  48.     cin >> n;
  49.     for(int i = 0; i < n; i++){
  50.         if(test())
  51.             cout << "true" << " ";
  52.         else
  53.             cout << "false" << " ";
  54.     }
  55.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment