Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. bool isCyclicRec(int i, vector < vector<int>>& gr, vector<bool>& recStack, vector<bool>& visited)
  9. {
  10. if (!visited[i])
  11. {
  12. recStack[i] = true;
  13. visited[i] = true;
  14.  
  15. for (auto child : gr[i])
  16. {
  17. if (!visited[child] && isCyclicRec(child, gr, recStack, visited))
  18. return true;
  19. else if (recStack[child])
  20. return true;
  21. }
  22. }
  23. recStack[i] = false;
  24. return false;
  25. }
  26.  
  27. void isCyclic(vector < vector<int>>& gr)
  28. {
  29. int n = gr.size();
  30. vector<bool> recStack(n, false);
  31. vector<bool> visited(n, false);
  32. bool hasCycle = false;
  33. for (int i = 0; i < n; i++)
  34. {
  35. if (isCyclicRec(i, gr, recStack, visited))
  36. {
  37. hasCycle = true;
  38. break;
  39. }
  40. }
  41. if (hasCycle)
  42. cout << "true ";
  43. else
  44. cout << "false ";
  45. }
  46.  
  47. int main() {
  48. int N;
  49. int v, e, u, w, t;
  50. cin >> N;
  51. while (N--)
  52. {
  53. cin >> v >> e;
  54. vector<vector<int>> gr(v+1);
  55. for (int i = 0; i < e; i++)
  56. {
  57. cin >> u >> t >> w;
  58. gr[u].push_back(t);
  59. }
  60. isCyclic(gr);
  61. }
  62. return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement