阿米巴是小强的好朋友。
阿米巴和小强在草原上捉蚂蚱。小强突然想,如果蚂蚱被他们捉灭绝了,那么吃蚂蚱的小鸟就会饿死,而捕食小鸟的猛禽也会跟着灭绝,从而引发一系列的生态灾难。
学过生物的阿米巴告诉小强,草原是一个极其稳定的生态系统。如果蚂蚱灭绝了,小鸟照样可以吃别的虫子,所以一个物种的灭绝并不一定会引发重大的灾难。
我们现在从专业一点的角度来看这个问题。我们用一种叫做食物网的有向图来描述生物之间的关系: 一个食物网有 N个点,代表 N 种生物,如果生物 x 可以吃生物 y,那么从 y向 x 连一个有向边。
这个图没有环。
图中有一些点没有连出边,这些点代表的生物都是生产者,可以通过光合作用来生存; 而有连出边的点代表的都是消费者,它们必须通过吃其他生物来生存。
如果某个消费者的所有食物都灭绝了,它会跟着灭绝。
我们定义一个生物在食物网中的“灾难值”为,如果它突然灭绝,那么会跟
着一起灭绝的生物的种数。
给定一个食物网,你要求出每个生物的灾难值。
【输入格式】
输入文件 catas.in 的第一行是一个正整数 N,表示生物的种数。生物从 1 标
号到 N。
接下来 N 行,每行描述了一个生物可以吃的其他生物的列表,格式为用空
格隔开的若干个数字,每个数字表示一种生物的标号,最后一个数字是 0 表示列
表的结束。
【输出格式】
输出文件 catas.out 包含N行,每行一个整数,表示每个生物的灾难值。
【样例输入】
5
0
1 0
1 0
2 3 0
2 0
【样例输出】
4
1
0
0
0
【样例说明】
样例输入描述了题目描述中举的例子。
【数据规模】
对 50%的数据,N ≤ 10000。
对 100%的数据,1 ≤ N ≤ 65534。
输入文件的大小不超过 1M。保证输入的食物网没有环。
BZ上的题干丢掉了,这里补充一下……
首先,我们可以对图进行拓扑排序,但是这样的复杂度是
我们要对他进行改造
还是,我们先拓扑排序,然后考虑,在什么样的情况下,他会被干掉
我们假设他的食物分别为
只有当他们的Lca被干掉的时候,他才可能死掉,否则的话必然存在一种食物存活,使得他也能活下去
我们可以按照拓扑序讲这些点插入到一个新的树里,每次把一个点
但是这里有一个小问题,就是动态的
时间复杂度
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
const int N = 240000+5;
const int M = 240000+5;
using namespace std;
int stack[N];
int top;
struct graph
{
int head[N],n,size[N];
int in[N],fa[N][20],depth[N];
queue <int> q;
struct line
{
int next,to;
line () {}
line (int _next,int _to)
:next(_next),to(_to){}
}edge[M];
inline void add(int x,int y)
{
static int cnt = 0;
edge[++cnt] = line(head[x],y);
head[x] = cnt;
}
void Topological_sorting()
{
for(int i=1;i<=n;++i)
if(!in[i])
q.push(i);
while(!q.empty())
{
int tt = q.front();
q.pop();
stack[++top] = tt;
for(int i=head[tt];i;i=edge[i].next)
if(!--in[edge[i].to])
q.push(edge[i].to);
}
}
int lca(int x,int y)
{
if(x==-1)return y;
if(depth[x] < depth[y])swap(x,y);
int tt = depth[x] - depth[y];
for(int i=0;i<20;++i)
if((1<<i)&tt)
x = fa[x][i];
if(x==y)return x;
for(int i=19;~i;--i)
if(fa[x][i]!=fa[y][i])
x = fa[x][i],y = fa[y][i];
return fa[x][0];
}
void Pre(int x)
{
for(int i=1;i<20;++i)
fa[x][i] = fa[fa[x][i-1]][i-1];
}
void DFS(int x)
{
size[x] = 1;
for(int i=head[x];i;i=edge[i].next)
if(edge[i].to!=fa[x][0])
DFS(edge[i].to),size[x] += size[edge[i].to];
}
}G1,G2;
void build()
{
for(int tmp = top;tmp>0;--tmp)
{
int x = stack[tmp];
int fa = -1;
for(int i=G1.head[x];i;i=G1.edge[i].next)
fa = G2.lca(fa,G1.edge[i].to);
if(fa == -1) fa = 0;
G2.add(fa,x);
G2.depth[x] = G2.depth[fa] + 1;
G2.fa[x][0] = fa;
G2.Pre(x);
}
}
inline int read()
{
int x=0,f=1;char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-')f=-1;ch = getchar();}
while(ch >='0' && ch <='9'){x=(x<<1)+(x<<3)+ch-'0';ch = getchar();}
return x*f;
}
int main()
{
int n = read();
G1.n = G2.n = n;
for(int i=1;i<=n;++i)
{
int tmp = read();
while(tmp)
{
G1.add(i,tmp);
G1.in[tmp]++;
tmp = read();
}
}
G1.Topological_sorting();
// for(int i=1;i<=top;++i)
// cout << stack[i] << endl;
build();
G2.DFS(0);
for(int i=1;i<=n;++i)
printf("%d\n",G2.size[i]-1);
}