码迷,mamicode.com
首页 > 其他好文 > 详细

[ZJOI2012]灾难

时间:2019-10-03 23:56:57      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:mes   dig   top   main   define   zjoi   queue   tchar   sort   

Description

[ZJOI2012]灾难

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]灾难

标签:mes   dig   top   main   define   zjoi   queue   tchar   sort   

原文地址:https://www.cnblogs.com/Agakiss/p/11621043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!