Advertisement
wurdalak007

Untitled

Feb 17th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. //
  2. // main.cpp
  3. // min_cycle
  4. //
  5. // Created by Матвей on 12.02.2018.
  6. // Copyright © 2018 Матвей. All rights reserved.
  7. //
  8.  
  9. #include <iostream>
  10. #include <vector>
  11. #include <stack>
  12. #include <queue>
  13. using namespace std;
  14.  
  15. class Graph {
  16. public:
  17. Graph( int n );
  18. ~Graph() = default;
  19. void AddEdge( int from, int to );
  20. int FindCycle();
  21. int BFS( int start );
  22. private:
  23. vector< vector<int> > graph;
  24. };
  25.  
  26. Graph::Graph( int n ): graph(n) {}
  27.  
  28. int Graph::BFS( int start ){
  29. queue<int> q;
  30. vector<bool> used( graph.size(), false );
  31. vector<int> parents(graph.size());
  32. vector<int> cycle_size(graph.size(), 0);
  33.  
  34. q.push(start);
  35. used[start] = true;
  36.  
  37. while( !q.empty() ) {
  38. int current_vert = q.front();
  39. q.pop();
  40. for( int i : graph[current_vert] ) {
  41. if( !used[i] ) {
  42. q.push(i);
  43. parents[i] = current_vert;
  44. cycle_size[i] = cycle_size[current_vert] + 1;
  45. used[i] = true;
  46. } else if( i!= parents[current_vert] ) {
  47. return cycle_size[i] + cycle_size[current_vert] + 1;
  48. }
  49. }
  50.  
  51. }
  52. return 10001;
  53. }
  54.  
  55. void Graph::AddEdge( int from, int to ) {
  56. graph[to].push_back(from);
  57. graph[from].push_back(to);
  58. }
  59.  
  60. int Graph::FindCycle() {
  61. int tmp_cycle = 0;
  62. int min_cycle = 10001;
  63.  
  64. for( int i = 0; i < graph.size(); i++ ) {
  65. tmp_cycle = BFS(i);
  66. if( tmp_cycle < min_cycle ) {
  67. min_cycle = tmp_cycle;
  68. }
  69. }
  70. if( min_cycle != 10001 ) {
  71. return tmp_cycle;
  72. } else {
  73. return -1;
  74. }
  75. }
  76.  
  77. int main() {
  78. int vertex = 0;
  79. int edges = 0;
  80.  
  81. cin >> vertex >> edges;
  82. Graph graph(vertex);
  83.  
  84. for( int i = 0; i < edges; i++ ) {
  85. int from = 0;
  86. int to = 0;
  87. cin >> from >> to;
  88. graph.AddEdge(from, to);
  89. }
  90. cout << graph.FindCycle();
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement