1. 程式人生 > >BZOJ4756: [Usaco2017 Jan]Promotion Counting(線段樹合並)

BZOJ4756: [Usaco2017 Jan]Promotion Counting(線段樹合並)

.com space lower clu return bzoj const bits motion

題意

題目鏈接

Sol

線段樹合並板子題

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 400000, SS = MAXN * 21;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, p[MAXN], fa[MAXN], root[MAXN], tot, ans[MAXN];
vector<int> v[MAXN];
int ls[SS], rs[SS], sum[SS];
void insert(int &k, int l, int r, int p, int v) {
    if(!k) k = ++tot;
    sum[k]++;
    if(l == r) return ;
    int mid = l +  r >> 1;
    if(p <= mid) insert(ls[k], l, mid, p, v);
    else insert(rs[k], mid + 1, r, p, v);
}
int Query(int k, int l, int r, int ql, int qr) {
    if(ql <= l && r <= qr) return sum[k];
    int mid = l + r >> 1;
    if(ql > mid) return Query(rs[k], mid + 1, r, ql, qr);
    else if(qr <= mid) return Query(ls[k], l, mid, ql, qr);
    else return Query(ls[k], l, mid, ql, qr) + Query(rs[k], mid + 1, r, ql, qr);
}
int Merge(int x, int y) {
    if(!x || !y) return x ^ y;
    ls[x] = Merge(ls[x], ls[y]);
    rs[x] = Merge(rs[x], rs[y]);
    sum[x] += sum[y];
    return x;
}
void dfs(int x) {
    for(int i = 0; i < v[x].size(); i++) {
        int to = v[x][i]; dfs(to);
        root[x] = Merge(root[x], root[to]);
    }
    ans[x] = Query(root[x], 1, N, p[x] + 1, N);
    insert(root[x], 1, N, p[x], 1);
}
void Des() {
    static int date[MAXN], num = 0;
    for(int i = 1; i <= N; i++) date[++num] = p[i];
    sort(date + 1, date + num + 1);
    num = unique(date + 1, date + num + 1) - date - 1;
    for(int i = 1; i <= N; i++) p[i] = lower_bound(date + 1, date + N + 1, p[i]) - date;
}
int main() {
    N = read();
    for(int i = 1; i <= N; i++) p[i] = read();
    Des();
    for(int i = 2; i <= N; i++) fa[i] = read(), v[fa[i]].push_back(i);
    dfs(1);
    for(int i = 1; i <= N; i++) printf("%d\n", ans[i]);
    return 0;
}
/*
*/

BZOJ4756: [Usaco2017 Jan]Promotion Counting(線段樹合並)