Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <unordered_map>
- using namespace std;
- bool hasCycle(unordered_map<int, vector<int>>& graph, vector<bool>& visited, vector<bool> pathVisited, int idx) {
- if(pathVisited[idx])
- return true;
- pathVisited[idx] = true;
- for(auto neighbour : graph[idx]){
- if(hasCycle(graph, visited, pathVisited, neighbour))
- return true;
- }
- pathVisited[idx] = false;
- visited[idx] = true;
- return false;
- }
- bool test(){
- int v, e, x, y, w;
- cin >> v >> e;
- unordered_map<int, vector<int>> graph;
- for(int i = 0; i < e; i++){
- cin >> x >> y >> w;
- graph[x - 1].push_back(y - 1);
- }
- vector<bool> visited(v, false);
- for(int i = 0; i < v; i++) {
- if(!visited[i]){
- vector<bool> pathVisited(v, false);
- if(hasCycle(graph, visited, pathVisited, i)){
- return true;
- }
- }
- }
- return false;
- }
- int main() {
- int n;
- cin >> n;
- for(int i = 0; i < n; i++){
- if(test())
- cout << "true" << " ";
- else
- cout << "false" << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment