您的位置:首页 > 其它

bzoj 2815: [ZJOI2012]灾难

2017-10-06 16:43 323 查看
题意:给出一个食物网,对于每个生物求出它灭绝后有多少种生物会灭绝。

题解:拓扑序+lca

先求出食物网的拓扑序,然后再建出灭绝树。灭绝树上假如一个节点灭绝,那么它的子树也会灭绝。为了满足这个性质,每个节点的父亲就要满足可以影响到它所有能吃的物种,也就是它们的lca。

代码:

#include<bits/stdc++.h>
using namespace std;

int n,num=0,fst[65536],in[65536],ans[65536];
struct edge
{
int x,y,n;
}e[65536];
struct pnt
{
int dep,fa[20];
}p[65536];
vector<int>a[65536],b,c[65536];
bool v[65536];
queue<int>q;

void ins(int x,int y)
{
e[++num]={x,y,fst[x]};
fst[x]=num;
}
int getlca(int x,int y)
{
if(p[x].dep<p[y].dep)
swap(x,y);
for(int i=19;i>=0;i--)
if((1<<i)<=p[x].dep-p[y].dep)
x=p[x].fa[i];
if(x==y)
return x;
for(int i=19;i>=0;i--)
if(p[x].fa[i]!=p[y].fa[i])
{
x=p[x].fa[i];
y=p[y].fa[i];
}
return p[x].fa[0];
}
void insert(int x)
{
if(c[x].empty())
{
return;
}
int lca=c[x][0];
for(int i=1;i<c[x].size();i++)
lca=getlca(lca,c[x][i]);
//  printf("%d %d\n",x,lca);
p[x].fa[0]=lca;
for(int i=1;i<20;i++)
p[x].fa[i]=p[p[x].fa[i-1]].fa[i-1];
p[x].dep=p[lca].dep+1;
ins(lca,x);
}
void dfs(int x)
{
ans[x]=1;
for(int i=fst[x];i;i=e[i].n)
{
int y=e[i].y;
dfs(y);
ans[x]+=ans[y];
}
}
int main()
{
memset(v,0,sizeof(v));
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
while(x)
{
a[x].push_back(i);
c[i].push_back(x);
in[i]++;
scanf("%d",&x);
}
}
for(int i=1;i<=n;i++)
if(!in[i])
q.push(i);
while(!q.empty())
{
int x=q.front();
b.push_back(x);
q.pop();
for(int i=0;i<a[x].size();i++)
{
in[a[x][i]]--;
if(!in[a[x][i]])
q.push(a[x][i]);
}
}/*
for(int i=0;i<n;i++)
printf("%d ",b[i]);
puts("");*/
for(int i=0;i<n;i++)
{
insert(b[i]);
}
for(int i=0;i<n;i++)
{
if(!ans[b[i]])
dfs(b[i]);
}
for(int i=1;i<=n;i++)
printf("%d\n",ans[i]-1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: