Advertisement
ainem

detect cycle in undirected graph

Aug 16th, 2021
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. /*    Never let anyone dull your sparkle...    */
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // type definition
  6. #define int long long
  7. using i64 = int64_t;
  8. typedef pair<int, int> ii;
  9. // constants
  10. constexpr int N = 2e6 + 2;
  11. constexpr int INF = 0x3f3f3f3f;
  12. constexpr int MOD = 1e9 + 7;
  13. constexpr float PI = 3.14;
  14. // possible moves
  15. constexpr int dx[8] = {1, 1, -1, -1, 0, 0, 1, -1};
  16. constexpr int dy[8] = {1, 0, -1, 0, 1, -1, -1, 1};
  17. // shortcuts
  18. #define pb push_back
  19. #define eb emplace_back
  20. #define mp make_pair
  21. #define fi first
  22. #define se second
  23. #define endl '\n'
  24. #define sz(x) i64(x.size())
  25. #define all(x) begin(x), end(x)
  26. #define rall(x) begin(x), end(x), greater<int>()
  27. // loop definition
  28. #define FOR(i, n, m) for (int i = n; i <= m; ++i)
  29. #define FORD(i, n, m) for (int i = n; i >= m; --i)
  30.  
  31. int n, m;
  32. std::vector<int> g[N];
  33.  
  34. bool BFS(int s, vector<bool> &visited) {
  35.     vector<int> parent(n, -1);
  36.     queue<int> q;
  37.     visited[s] = true;
  38.     q.push(s);
  39.     while (!q.empty()) {
  40.         int u = q.front();
  41.         q.pop();
  42.         for (int v : g[u]) {
  43.             if (!visited[v]) {
  44.                 visited[v] = true;
  45.                 q.push(v);
  46.                 parent[v] = u;
  47.             }
  48.             else if (parent[u] != v)
  49.                 return true;
  50.         }
  51.     }
  52.     return false;
  53. }
  54.  
  55. bool isCyclic() {
  56.     vector<bool> visited(n, false);
  57.     FOR(i, 1, n) {
  58.         if (!visited[i] && BFS(i, visited)) {
  59.             return true;
  60.         }
  61.     }
  62.     return false;
  63. }
  64. int32_t main(void) {
  65.     ios_base::sync_with_stdio(false);
  66.     cin.tie(nullptr);
  67.  
  68.     //freopen("main.INP", "r", stdin);
  69.     //freopen("main.OUT", "w", stdout);
  70.  
  71.     cin >> n >> m;
  72.     while (m--) {
  73.         int x, y; cin >> x >> y;
  74.         g[x].pb(y);
  75.         g[y].pb(x);
  76.     }
  77.  
  78.     cout << (isCyclic() ? "YES" : "NO");
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement