bzoj2815 灾难 拓扑排序&lca

       按照出题人的题解,我们需要构造一颗“灭绝树”。即对于灭绝树上的两个点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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值