Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- using namespace std;
- bool isCyclicRec(int i, vector < vector<int>>& gr, vector<bool>& recStack, vector<bool>& visited)
- {
- if (!visited[i])
- {
- recStack[i] = true;
- visited[i] = true;
- for (auto child : gr[i])
- {
- if (!visited[child] && isCyclicRec(child, gr, recStack, visited))
- return true;
- else if (recStack[child])
- return true;
- }
- }
- recStack[i] = false;
- return false;
- }
- void isCyclic(vector < vector<int>>& gr)
- {
- int n = gr.size();
- vector<bool> recStack(n, false);
- vector<bool> visited(n, false);
- bool hasCycle = false;
- for (int i = 0; i < n; i++)
- {
- if (isCyclicRec(i, gr, recStack, visited))
- {
- hasCycle = true;
- break;
- }
- }
- if (hasCycle)
- cout << "true ";
- else
- cout << "false ";
- }
- int main() {
- int N;
- int v, e, u, w, t;
- cin >> N;
- while (N--)
- {
- cin >> v >> e;
- vector<vector<int>> gr(v+1);
- for (int i = 0; i < e; i++)
- {
- cin >> u >> t >> w;
- gr[u].push_back(t);
- }
- isCyclic(gr);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement