Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- #define _test int _TEST; cin>>_TEST; while(_TEST--)
- #define ff first
- #define ss second
- #define pb push_back
- #define ppb pop_back
- int main()
- {
- int n;
- cin>>n;
- vector<vector<int>> graph(n);
- for(int i=0; i<n; i++)
- {
- int v;
- cin>>v;
- v--;
- graph[i].pb(v);
- }
- vector<int> vis(n);
- vector<int> prev(n, -1);
- function<void(int)> DFS = [&](int u)
- {
- vis[u] = 1;
- for(auto v: graph[u])
- {
- if(!vis[v])
- {
- prev[v] = u;
- DFS(v);
- }
- else
- {
- vector<int> ans;
- int x = u;
- while(x != v)
- {
- ans.pb(x+1);
- x = prev[x];
- }
- ans.pb(v+1);
- reverse(ans.begin(), ans.end());
- cout<<ans.size()<<"\n";
- for(auto e: ans) cout<<e<<" ";
- cout<<"\n";
- exit(0);
- }
- }
- vis[u] = 2;
- };
- for(int i=0; i<n; i++)
- {
- if(!vis[i])
- DFS(i);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment