fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define nl '\n'
  4. #define ll long long
  5.  
  6. void fastio() {
  7. ios_base::sync_with_stdio(false);
  8. cin.tie(nullptr);
  9. cout.tie(nullptr);
  10. }
  11. vector<bool>visited;
  12. vector<vector<int>>adj;
  13.  
  14. bool cyclic = false;
  15. void dfs(int node,int p){
  16. visited[node]=true;
  17.  
  18. for(auto child : adj[node]){
  19. if(child == p)
  20. continue;
  21.  
  22. if(!visited[child]){
  23. dfs(child,node);
  24. }
  25. else{
  26. cyclic =true;
  27. }
  28. }
  29. }
  30. void solve() {
  31. int n,e;cin >> n>> e;
  32. int u,v;
  33. adj.assign(n+1,{});
  34. visited.assign(n+1,false);
  35. for(int i=0;i<e;i++){
  36. cin >> u >> v;
  37. adj[u].push_back(v);
  38. adj[v].push_back(u);
  39. }
  40.  
  41.  
  42. for(int i=1;i<=n;i++){
  43. if(!visited[i]){
  44. dfs(i,i);
  45. }
  46.  
  47. }
  48. if(cyclic) cout <<"There is a cycle\n";
  49. else cout <<"There is not a cycle\n";
  50.  
  51. }
  52.  
  53. int main() {
  54. fastio();
  55. int t=1;
  56. //cin >> t;
  57. while (t--)
  58. solve();
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0.01s 5288KB
stdin
4 4
1 2
2 3
3 4
4 1
stdout
There is a cycle