Advertisement
arsovski

Untitled

Jan 23rd, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include<list>
  7. using namespace std;
  8.  
  9. int number_nodes,number_edges;
  10. std::vector<std::list<int> > graph;
  11. std::vector<char> visited;
  12.  
  13. void add_connection(int from,int to ,int weight){
  14. graph[from].push_back(to);
  15.  
  16. }
  17.  
  18. void dfs(int from,bool& has_cycle){
  19. visited[from] ='o';
  20.  
  21. if(has_cycle)
  22. return;
  23.  
  24. for(auto neighbor:graph[from]){
  25. if(visited[from] =='u'){
  26. dfs(from,has_cycle);
  27. }
  28. else if (visited[from]=='o')
  29. {
  30. has_cycle=true;
  31. return;
  32. }
  33. }
  34.  
  35. visited[from]='c';
  36.  
  37. }
  38.  
  39. bool find_cycle(){
  40.  
  41. bool has_cycle=false;
  42. for(int i=0;i<graph.size();i++){
  43. if(has_cycle)
  44. return true;
  45.  
  46. if(visited[i] == 'u'){
  47.  
  48. dfs(i,has_cycle);
  49. }
  50. }
  51.  
  52. return false;
  53. }
  54.  
  55.  
  56. int main() {
  57. /* Enter your code here. Read input from STDIN. Print output to STDOUT */
  58. int graph_count;
  59. std::cin>>graph_count;
  60.  
  61. for(int i=0;i<graph_count;i++){
  62.  
  63. graph.clear();
  64. visited.clear();
  65.  
  66.  
  67. std::cin>>number_nodes>>number_edges;
  68.  
  69. graph.resize(number_nodes+1);
  70. visited.resize(number_nodes+1,'u');
  71.  
  72. for(int j=0;j<number_edges;j++){
  73. int from,to,weight;
  74. std::cin>>from>>to>>weight;
  75. add_connection(from,to,weight);
  76. }
  77.  
  78. bool has_cycle = find_cycle();
  79.  
  80. if(has_cycle)
  81. std::cout<<"true ";
  82. else
  83. std::cout<<"false ";
  84.  
  85.  
  86. }
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement