大意: 给定森林, 要求构造一个表, 满足对于每个$x$, 表中第一次出现的$x$的祖先(包括$x$)是$a_x$.
刚开始还想着直接暴力分块优化一下连边, 最后按拓扑序输出...
实际上可以发现$a_x$要么等于$x$, 要么等于$fa_x$, 直接dfs一边就好了...
#include <iostream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ' ' using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} //head #ifdef ONLINE_JUDGE const int N = 1e6+10; #else const int N = 111; #endif int n, m; vector<int> g[N]; int s[N], vis[N], a[N]; void dfs(int x) { if (vis[x]) return; vis[x] = 1; for (int y:g[x]) { if (a[y]!=y&&a[y]!=a[x]) puts("-1"),exit(0); dfs(y); } if (a[x]==x) s[++*s]=x; } int main() { scanf("%d%d", &n, &m); REP(i,1,m) { int u, v; scanf("%d%d", &u, &v); g[u].pb(v); } REP(i,1,n) scanf("%d", a+i); REP(i,1,n) dfs(i); printf("%d ", *s); REP(i,1,*s) printf("%d ", s[i]); }