USACO 2017 Platinum January P1. Promotion Counting

Bitmask DP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <bits/stdc++.h>
using namespace std;

int N;
vector<vector<int>> adj;
vector<int> prevnum, rating, ans, parent;
int countval = 0;
vector<int> bit;

// bit functions
void updateBIT(int a, int b) {
    while (a <= N) { bit[a] += b; a += (a & (-a));}
}

int query(int a) {
    int r = 0;
    while (a > 0) {r += bit[a]; a = a - (a & (-a));} return r;
}

void dfs(int node) {
    prevnum[node] = query(N) - query(rating[node]);
    for (auto child : adj[node]) {
        countval++;
        dfs(child);
    }
    ans[node] = query(N) - query(rating[node]) - prevnum[node];
    updateBIT(rating[node], 1);
}

int main() {
    ifstream cin("promote.in");
    ofstream cout("promote.out");

    cin >> N;
    adj.resize(N + 1);
    rating.resize(N + 1);
    bit.resize(N + 1);
    parent.resize(N + 1, -1);
    prevnum.resize(N + 1);
    ans.resize(N + 1);

    vector<pair<int, int>> old(N + 1);
    for (int i = 1; i < N + 1; i++) {
        cin >> old[i].first;
        old[i].second = i;
    }

    for (int i = 2; i < N + 1; i++) {
        int p;
        cin >> p;
        adj[p].push_back(i);
    }

    // compression
    sort(old.begin(), old.end());
    for (int i = 1; i < N + 1; i++) {
        rating[old[i].second] = i;
    }
    dfs(1);
    for (int i = 1; i <= N; i++) {
        cout << ans[i] << endl;
    }
}