$dfs $, subsequent traversal.
If a node $a[i]=i$, then $i$ 's successor $a[i]$ to $i$ until a new successor $j$ appears, $a [j]=j$. Use this to determine whether there is a solution.
If there is a solution, then only the output of the sequential traversal of the results can be.
#pragmaComment (linker, "/stack:1024000000,1024000000")#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<vector>#include<map>#include<Set>#include<queue>#include<stack>#include<iostream>using namespaceStd;typedefLong LongLL;Const DoublePi=acos (-1.0), eps=1e-6;voidFile () {freopen ("D:\\in.txt","R", stdin); Freopen ("D:\\out.txt","W", stdout);} Template<classT>inlinevoidRead (T &x) { Charc = GetChar (); x =0; while(!isdigit (c)) C =GetChar (); while(IsDigit (c)) {x = x *Ten+ C-'0'; c =GetChar ();}}Const intmaxn=100010;intM,n,k,a[maxn],r[maxn];vector<int>G[MAXN];BOOLFlag[maxn],fail,f[maxn];vector<int>ans;voidDfsintXinty) { if(a[x]==x) y=x; Else{if(a[x]!=y) fail=1; } for(intI=0; I<g[x].size (); i++) DFS (g[x][i],y); if(F[x]) ans.push_back (x);}intMain () {scanf ("%d%d",&n,&m); for(intI=1; i<=m;i++) { intU,v; scanf"%d%d",&u,&v); G[u].push_back (v); R[V]++; } for(intI=1; i<=n;i++) {scanf ("%d", &a[i]); f[a[i]]=1; } for(intI=1; i<=n;i++)if(r[i]==0) DFS (i,i); if(fail) printf ("-1\n"); Else{printf ("%d\n", Ans.size ()); for(intI=0; I<ans.size (); i++) printf ("%d\n", Ans[i]); } return 0;}
Codeforces 681D Gifts by the List