fork download
  1. #include <bits/stdc++.h>
  2. #define F first
  3. #define S second
  4. #define el cout << '\n'
  5. #define maxn 100005
  6. #define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(0);
  7. #define For(i,a,b) for ( int i = a; i <= b; i++)
  8. #define ll long long
  9. #define MOD 100000007
  10. using namespace std;
  11.  
  12. vector < int > a[maxn];
  13. int m,n,s,t,check=0;
  14. int trace[maxn];
  15. int used[maxn];
  16.  
  17. void DFS(int s, int t)
  18. {
  19. used[s] = 1;
  20. for(int v : a[s])
  21. {
  22. if (used[s] == 0)
  23. {
  24. trace[v] = s;
  25. DFS(v, t);
  26. }
  27. }
  28.  
  29. if (used[t] == 1)
  30. {
  31. check = 1;
  32. vector <int> res;
  33. int u = t;
  34. while (u != s)
  35. {
  36. res.push_back(u);
  37. u = trace[u];
  38. }
  39. res.push_back(s);
  40. cout << res.size(); el;
  41. reverse(res.begin(), res.end());
  42. for(int i : res) cout << i << " ";
  43. cout << s;
  44. }
  45. }
  46.  
  47. int main()
  48. {
  49. faster
  50. cin >> n;
  51. For(i,1,n)
  52. {
  53. int u, v;
  54. cin >> u >> v;
  55. a[u].push_back(v);
  56. a[v].push_back(u);
  57. }
  58. for(int u = 1; u <= n; u++)
  59. {
  60. for(int v : a[u])
  61. {
  62. DFS(u, v);
  63. if (check == 1) break;
  64. else
  65. {
  66. fill(trace, trace + n + 1, 0);
  67. fill(used, used + n + 1, 0);
  68. }
  69. }
  70. if (check == 1) break;
  71. }
  72. if (check == 0) cout << "NO";
  73. }
  74.  
Success #stdin #stdout 0.01s 6092KB
stdin
Standard input is empty
stdout
NO