Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include<list>
- using namespace std;
- int number_nodes,number_edges;
- std::vector<std::list<int> > graph;
- std::vector<char> visited;
- void add_connection(int from,int to ,int weight){
- graph[from].push_back(to);
- }
- void dfs(int from,bool& has_cycle){
- visited[from] ='o';
- if(has_cycle)
- return;
- for(auto neighbor:graph[from]){
- if(visited[from] =='u'){
- dfs(from,has_cycle);
- }
- else if (visited[from]=='o')
- {
- has_cycle=true;
- return;
- }
- }
- visited[from]='c';
- }
- bool find_cycle(){
- bool has_cycle=false;
- for(int i=0;i<graph.size();i++){
- if(has_cycle)
- return true;
- if(visited[i] == 'u'){
- dfs(i,has_cycle);
- }
- }
- return false;
- }
- int main() {
- /* Enter your code here. Read input from STDIN. Print output to STDOUT */
- int graph_count;
- std::cin>>graph_count;
- for(int i=0;i<graph_count;i++){
- graph.clear();
- visited.clear();
- std::cin>>number_nodes>>number_edges;
- graph.resize(number_nodes+1);
- visited.resize(number_nodes+1,'u');
- for(int j=0;j<number_edges;j++){
- int from,to,weight;
- std::cin>>from>>to>>weight;
- add_connection(from,to,weight);
- }
- bool has_cycle = find_cycle();
- if(has_cycle)
- std::cout<<"true ";
- else
- std::cout<<"false ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement