题意
给出一个有向无环图,问把每个点分别删掉后有多少个点不能从入读为0的点到达。
n<=100000
分析
直接把支配树建出来,然后一个点的答案就是它在支配树上的size-1.
那什么叫支配树呢?对于一个给定的图,我们定一个点S作为原点,若对于两个不同的点x,y,如果想要到达x必须要经过y则称y支配x,显然S支配所有点,其中所有点中离x最近的支配称为x的支配点,每个点向他的支配点连一条边构成的树就是支配树。
那么对于一个DAG怎么构建支配树呢?
我们先拓扑排序一下,从入度为0的点开始加入到树中,每加入一个点就考虑所有能到达他的点,显然这些点在支配树里面的最近公共祖先就是当前点的支配点,然后再更新一下倍增数组即可。
代码
#include <bits/stdc++.h>
const int N = 100005;
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 * 10 + ch - '0'; ch = getchar();}
return x * f;
}
struct Edge
{
int to,next;
}e[N * 30];
int pre[N],next[N];
int cnt;
void add(int x,int y)
{
e[++cnt].to = y, e[cnt].next = next[x], next[x] = cnt;
e[++cnt].to = x, e[cnt].next = pre[y], pre[y] = cnt;
}
int n;
int d[N];
int a[N];
void topSort()
{
std::queue<int> Q;
Q.push(n + 1);
int top = 0;
while (!Q.empty())
{
int x = Q.front();
Q.pop();
a[++top] = x;
for (int i = next[x]; i; i = e[i].next)
{
d[e[i].to]--;
if (!d[e[i].to])
Q.push(e[i].to);
}
}
}
int fa[N][20];
int dep[N];
int lca(int x,int y)
{
if (dep[x] < dep[y])
std::swap(x,y);
for (int i = 16; i >= 0; i--)
if (dep[fa[x][i]] >= dep[y])
x = fa[x][i];
if (x == y)
return x;
for (int i = 16; i >= 0; i--)
if (fa[x][i] != fa[y][i])
x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
int size[N];
int main()
{
n = read();
for (int i = 1; i <= n; i++)
{
int x = read();
while (x)
{
add(x,i);
x = read();
d[i]++;
}
}
for (int i = 1; i <= n; i++)
if (!d[i])
add(n + 1, i), d[i]++;
topSort();
for (int i = 1; i <= n + 1; i++)
{
int x = a[i], y = 0;
for (int j = pre[x]; j; j = e[j].next)
if (!y)
y = e[j].to;
else y = lca(e[j].to, y);
fa[x][0] = y;
dep[x] = dep[y] + 1;
for (int j = 1; j <= 16; j++)
{
fa[x][j] = fa[fa[x][j - 1]][j - 1];
}
}
for (int i = n + 1; i >= 1; i--)
size[a[i]]++, size[fa[a[i]][0]] += size[a[i]];
for (int i = 1; i <= n; i++)
printf("%d\n",size[i] - 1);
}