BZOJ传送门
洛谷传送门
解析:
其实就是要在 D A G DAG DAG上求一个支配树。
不过我们并不清楚哪些点是起始点,所以建立虚点 0 0 0,向所有入度为 0 0 0的点连边。求出以 0 0 0为根的支配树,然后 d f s dfs dfs求出树上的 s i z siz siz,然后就没了。。。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define re register
#define gc get_char
#define pc put_char
#define cs const
namespace IO{
namespace IOONLY{
cs int Rlen=1<<18|1;
char buf[Rlen],*p1,*p2;
char obuf[Rlen],*p3=obuf;
}
inline char get_char(){
using namespace IOONLY;
return (p1==p2)&&(p2=(p1=buf)+fread(buf,1,Rlen,stdin),p1==p2)?EOF:*p1++;
}
inline void put_char(char c){
using namespace IOONLY;
*p3++=c;
if(p3==obuf+Rlen)fwrite(obuf,1,Rlen,stdout),p3=obuf;
}
inline void FLUSH(){
using namespace IOONLY;
fwrite(obuf,1,p3-obuf,stdout),p3=obuf;
}
inline int getint(){
re int num;
re char c;
while(!isdigit(c=gc()));num=c^48;
while(isdigit(c=gc()))num=(num+(num<<2)<<1)+(c^48);
return num;
}
inline void outint(int a){
static char ch[23];
if(a==0)pc('0');
while(a)ch[++ch[0]]=a-a/10*10,a/=10;
while(ch[0])pc(ch[ch[0]--]^48);
}
}
using namespace IO;
cs int N=1<<16|4;
struct graph{
vector<int> edge[N];
inline void addedge(int u,int v){
edge[u].push_back(v);
}
}g,revg,ng,dt;
int in[N],dfn[N],id[N],fa[N],dfs_clock;
void dfs(int u) {
id[dfn[u]=++dfs_clock]=u;
for(int re e=0,v;e<g.edge[u].size();++e){
v=g.edge[u][e];
if(dfn[v])continue;
fa[v]=u,dfs(v);
}
}
int semi[N],idom[N],bel[N],val[N];
inline int getfa(int x){
if(x==bel[x])return x;
int tmp=getfa(bel[x]);
if(dfn[semi[val[bel[x]]]]<dfn[semi[val[x]]])val[x]=val[bel[x]];
return bel[x]=tmp;
}
inline void tarjan(){
for(int re i=dfs_clock;i>1;--i){
int u=id[i];
for(int re e=0,v;e<revg.edge[u].size();++e){
v=revg.edge[u][e];
if(!dfn[v])continue;
getfa(v);
if(dfn[semi[val[v]]]<dfn[semi[u]])semi[u]=semi[val[v]];
}
ng.addedge(semi[u],u);
bel[u]=fa[u];
u=fa[u];
for(int re e=0,v;e<ng.edge[u].size();++e){
v=ng.edge[u][e];
getfa(v);
if(semi[val[v]]==u)idom[v]=u;
else idom[v]=val[v];
}
}
for(int re i=2;i<=dfs_clock;++i){
int u=id[i];
if(idom[u]!=semi[u])idom[u]=idom[idom[u]];
}
}
int siz[N];
void get_siz(int u){
siz[u]=1;
for(int re e=0,v;e<dt.edge[u].size();++e){
v=dt.edge[u][e];
get_siz(v);
siz[u]+=siz[v];
}
}
int n;
signed main(){
n=getint();
for(int re i=1,x;i<=n;++i){
while(x=getint())++in[i],g.addedge(x,i),revg.addedge(i,x);
}
for(int re i=1;i<=n;++i)if(!in[i])g.addedge(0,i),revg.addedge(i,0);
for(int re i=1;i<=n;++i)semi[i]=bel[i]=val[i]=i;
dfs(0);
tarjan();
for(int re i=1;i<=n;++i)dt.addedge(idom[i],i);
get_siz(0);
for(int re i=1;i<=n;++i)outint(siz[i]-1),pc('\n');
FLUSH();
return 0;
}