D_L3

Цикличен граф

Jan 27th, 2024
1,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 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 dfc(vector<bool>& visited, vector<bool>& pathVisited, int start, unordered_map<int, vector<int>>& graph){
  11.     if(pathVisited[start])
  12.         return true;
  13.     pathVisited[start] = true;
  14.     for(int neighbour : graph[start]){
  15.         if(dfc(visited, pathVisited, neighbour, graph))
  16.             return true;
  17.     }
  18.     pathVisited[start] = false;
  19.     visited[start] = true;
  20.     return false;
  21. }
  22.  
  23. bool isCyclic(unordered_map<int, vector<int>>& graph, int v){
  24.     vector<bool> visited(v, false);
  25.     for(int i = 0; i < v; i++) {
  26.         if(!visited[i]){
  27.             vector<bool> pathVisited(v, false);
  28.             if(dfc(visited, pathVisited, i, graph))
  29.                 return true;
  30.         }
  31.     }
  32.     return false;
  33. }
  34.  
  35. bool play(){
  36.     int v, e;
  37.     int a, b, c;
  38.     cin >> v >> e;
  39.     unordered_map<int, vector<int>> graph;
  40.    
  41.     for(int i = 0; i < e; i++){
  42.         cin >> a >> b >> c;
  43.         graph[a].push_back(b);
  44.     }
  45.    
  46.     return isCyclic(graph, v);
  47. }
  48.  
  49. int main() {
  50.     int n;
  51.     cin >> n;
  52.     for(int i = 0; i < n; i++){
  53.         if(play())
  54.             cout << "true ";
  55.         else
  56.             cout << "false ";
  57.     }
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment