Advertisement
wurdalak007

Untitled

Feb 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 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. int n = (int)graph.size();
  30. queue<int> q;
  31. vector<bool> used( n, false );
  32. vector<int> parents(n);
  33. vector<int> cycle_size(n, 10001);
  34.  
  35. q.push(start);
  36. used[start] = true;
  37. cycle_size[start] = 0;
  38. while( !q.empty() ) {
  39. int current_vert = q.front();
  40. q.pop();
  41. for( int j = 0; j < graph[current_vert].size(); j++ ) {
  42. int i = graph[current_vert][j];
  43. if( used[i] && i != parents[current_vert] ) {
  44. return cycle_size[i] + cycle_size[current_vert] + 1;
  45. } else if( !used[i] ) {
  46. q.push(i);
  47. parents[i] = current_vert;
  48. cycle_size[i] = cycle_size[current_vert] + 1;
  49. used[i] = true;
  50. }
  51. }
  52.  
  53. }
  54. return 10001;
  55. }
  56.  
  57. void Graph::AddEdge( int from, int to ) {
  58. graph[to].push_back(from);
  59. graph[from].push_back(to);
  60. }
  61.  
  62. int Graph::FindCycle() {
  63. int tmp_cycle = 0;
  64. int min_cycle = 10001;
  65.  
  66. for( int i = 0; i < graph.size(); i++ ) {
  67. tmp_cycle = BFS(i);
  68. if( tmp_cycle < min_cycle ) {
  69. min_cycle = tmp_cycle;
  70. }
  71. }
  72. if( min_cycle != 10001 ) {
  73. return tmp_cycle;
  74. } else {
  75. return -1;
  76. }
  77. }
  78.  
  79. int main() {
  80. int vertex = 0;
  81. int edges = 0;
  82.  
  83. cin >> vertex >> edges;
  84. Graph graph(vertex);
  85.  
  86. for( int i = 0; i < edges; i++ ) {
  87. int from = 0;
  88. int to = 0;
  89. cin >> from >> to;
  90. graph.AddEdge(from, to);
  91. }
  92. cout << graph.FindCycle();
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement