按照出题人的题解,我们需要构造一颗“灭绝树”。即对于灭绝树上的两个点x,y,如果x为y的祖先,则x的灭亡会直接导致y的灭亡。下面进行构造:
首先进行拓扑排序,然后按照排序的逆序构造,保证对于图中的任意x->{y},都能使x构造前,{y}已经完成构造。然后找到{y}在灭绝树上面的位置,显然{y}在灭绝树上的公共祖先的灭绝会导致{y}全部灭绝进而导致x灭绝。于是可以求它们的lca,那么lca就是x在灭绝树上面的祖先。最后跑一边dfs统计子树大小即可。
实际上,这是求有向图必经点的一个特殊问题(无环),实际上可以直接用支配树解决(然而窝太弱不会)。也是O(N)级别的。
AC代码如下:
#include<iostream> #include<cstdio> #include<cstring> #define N 100005 using namespace std; int n,m,tot,sz[N],h[N],bin[20],pnt[N<<4],nxt[N<<4],d[N],fa[N][17],etr[N]; int read(){ int x=0; char ch=getchar(); while (ch<'0' || ch>'9') ch=getchar(); while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); } return x; } int lca(int x,int y){ if (x<0) return y; if (d[x]<d[y]) swap(x,y); int tmp=d[x]-d[y],i; for (i=0; i<17; i++) if (tmp&bin[i]) x=fa[x][i]; for (i=16; ~i; i--) if (fa[x][i]!=fa[y][i]){ x=fa[x][i]; y=fa[y][i]; } return (x==y)?x:fa[x][0]; } struct node{ int fst[N]; void add(int x,int y){ pnt[++tot]=y; nxt[tot]=fst[x]; fst[x]=tot; etr[y]++; } void topo(){ int head=0,tail=0,i; for (i=1; i<=n; i++) if (!etr[i]) h[++tail]=i; while (head<tail){ int x=h[++head],p; for (p=fst[x]; p; p=nxt[p]){ int y=pnt[p]; etr[y]--; if (!etr[y]) h[++tail]=y; } } } void extend(int x,int y){ add(x,y); d[y]=d[x]+1; fa[y][0]=x; int i; for (i=1; i<17; i++) fa[y][i]=fa[fa[y][i-1]][i-1]; } void dfs(int x){ sz[x]=1; int p; for (p=fst[x]; p; p=nxt[p]){ dfs(pnt[p]); sz[x]+=sz[pnt[p]]; } } }g1,g2; void build(){ int i; bin[0]=1; for (i=1; i<17; i++) bin[i]=bin[i-1]<<1; for (i=n; i; i--){ int x=h[i],p,tmp=-1; for (p=g1.fst[x]; p; p=nxt[p]) tmp=lca(tmp,pnt[p]); g2.extend(max(tmp,0),x); } } int main(){ n=read(); int i; for (i=1; i<=n; i++){ int x=read(); for (; x; x=read()) g1.add(i,x); } g1.topo(); build(); g2.dfs(0); for (i=1; i<=n; i++) printf("%d\n",sz[i]-1); return 0; }
by lych
2016.2.26