【USACO2017JAN】 Promotion Counting
【题目链接】
【算法】
离散化 + dfs + 树状数组
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 100000 int N,i,lth,x,pos; int a[MAXN+10],tmp[MAXN+10],rank[MAXN+10],ans[MAXN+10]; vector<int> E[MAXN+10]; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } struct BinaryIndexedTree { int bit[MAXN+10]; int lowbit(int x) { return x & -x; } inline void modify(int pos) { int i; for (i = pos; i <= N; i += lowbit(i)) bit[i]++; } inline int query(int pos) { int i,ret = 0; for (i = pos; i; i -= lowbit(i)) ret += bit[i]; return ret; } } BIT; inline void dfs(int x) { int i; BIT.modify(rank[x]); ans[x] = -BIT.query(rank[x]-1); for (i = 0; i < E[x].size(); i++) dfs(E[x][i]); ans[x] += BIT.query(rank[x]-1); } int main() { read(N); for (i = 1; i <= N; i++) { read(a[i]); tmp[i] = a[i]; } sort(tmp+1,tmp+N+1); for (i = 1; i <= N; i++) { if (tmp[i] != tmp[i-1]) tmp[++lth] = tmp[i]; } for (i = 1; i <= N; i++) { pos = lower_bound(tmp+1,tmp+lth+1,a[i]) - tmp; rank[i] = N - pos + 1; } for (i = 2; i <= N; i++) { read(x); E[x].push_back(i); } dfs(1); for (i = 1; i <= N; i++) writeln(ans[i]); return 0; }