Using Tarjan to find strong connected components, a DAG is formed after a strong connected component point has an equivalent contraction point, and a number of points a with a degree of 0 are calculated.
With a size of 0 B, take one of them. A case in which the number of strongly connected components is 1.
It's easier to read the Tarjan algorithm later.
#include <bits/stdc++.h>using namespacestd;Const intMAXN = 2e4+5;Const intMAXM = 5e4+5;inthead[maxn],nxt[maxm],to[maxm],ecnt;voidAddedge (intUintv) {nxt[ecnt]=Head[u]; TO[ECNT]=v; Head[u]= ecnt++;}voidInitgraph (intN) {memset (head,-1,sizeof(int) * (n+1)); ECNT =0;}intSccno[maxn],pre[maxn],low[maxn],dfs_clock,scc_cnt;stack<int>Stk;voidTarjan (intu) {Pre[u]= Low[u] = + +Dfs_clock; Stk.push (U); for(inti = Head[u]; ~i; i =Nxt[i]) { intv =To[i]; if(!Pre[v]) {Tarjan (v); Low[u]=min (low[u],low[v]); }Else if(!Sccno[v]) {Low[u]=min (low[u],pre[v]); } } if(Low[u] = =Pre[u]) {scc_cnt++; while(Stk.size ()) {intx =stk.top (); Stk.pop (); SCCNO[X]=scc_cnt; if(x = = u) Break; } }}voidFIND_SCC (intN) {memset (PRE,0,sizeof(int) * (n+1)); memset (Sccno,0,sizeof(int) * (n+1)); Scc_cnt= Dfs_clock =0; for(inti =0; I < n; i++){ if(!Pre[i]) Tarjan (i); }}intIND[MAXN],OUTD[MAXN];intMain () {//freopen ("In.txt", "R", stdin); intT scanf"%d",&T); while(t--){ intN,m; scanf"%d%d",&n,&m); Initgraph (n); for(inti =0; I < m; i++){ intU,v; scanf"%d%d",&u,&v); Addedge (U-1, V-1); } FIND_SCC (n); if(scc_cnt = =1) {printf ("0\n");Continue; } for(inti =1; I <= scc_cnt; i++) Ind[i] = outd[i] =0; for(intU =0; U < n; u++){ for(inti = Head[u]; ~i; i =Nxt[i]) { intv =To[i]; if(Sccno[u]! = Sccno[v]) outd[sccno[u]]++,ind[sccno[v]]++; } } intA =0, B =0; for(inti =1; I <= scc_cnt; i++){ if(!outd[i]) b++; if(!ind[i]) a++; } printf ("%d\n", Max (A, b)); } return 0;}
Uvalive 4287 proving equivalence