[ZJOI2012]灾难
Posted agakiss
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[ZJOI2012]灾难相关的知识,希望对你有一定的参考价值。
Description
Solution
我们可
反向建图
Code
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define MAXN 1000010
struct rec
int nxt, ver;
t[MAXN];
int n, cnt, s;
int head[MAXN], in[MAXN], size[MAXN], d[MAXN], lca[MAXN][21], h[MAXN];
queue <int> q;
inline int read()
int s = 0, w = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
return s * w;
inline void add(int u, int v)
t[++cnt].nxt = head[u], t[cnt].ver = v, head[u] = cnt;
inline void TopSort()
for (register int i = 1; i <= n; i++)
if (!in[i]) q.push(i);
while (!q.empty())
int u = q.front();
q.pop();
h[++s] = u;
for (register int i = head[u]; i; i = t[i].nxt)
int v = t[i].ver;
if (!(--in[v])) q.push(v);
inline int LCA(int u, int v)
if (d[u] < d[v]) swap(u, v);
for (register int i = 20; i >= 0; i--)
if (d[lca[u][i]] >= d[v]) u = lca[u][i];
if (u == v) return u;
for (register int i = 20; i >= 0; i--)
if (lca[u][i] != lca[v][i]) u = lca[u][i], v = lca[v][i];
return lca[u][0];
int main()
n = read();
for (register int i = 1; i <= n; i++)
int x = read();
while (x) ++in[x], add(i, x), x = read();
TopSort();
for (register int i = n; i; i--)
int u = h[i], x = t[head[u]].ver;
for (register int j = t[head[u]].nxt; j; j = t[j].nxt)
int v = t[j].ver;
x = LCA(x, v);
lca[u][0] = x, d[u] = d[x] + 1;
for (register int j = 1; j <= 20; j++) lca[u][j] = lca[lca[u][j - 1]][j - 1];
for (register int i = 1; i <= n; i++) ++size[h[i]], size[lca[h[i]][0]] += size[h[i]];
for (register int i = 1; i <= n; i++) printf("%d\n", size[i] - 1);
return 0;
以上是关于[ZJOI2012]灾难的主要内容,如果未能解决你的问题,请参考以下文章