From f738250c1109eccd0a69585d9401b3283d4e4a1a Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Thu, 15 Sep 2022 15:41:28 +0800 Subject: [PATCH] P3605 [USACO17JAN]Promotion Counting P https://www.luogu.com.cn/record/86666473 --- Luogu/P3605/P3605.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Luogu/P3605/P3605.cpp diff --git a/Luogu/P3605/P3605.cpp b/Luogu/P3605/P3605.cpp new file mode 100644 index 00000000..0282f9ec --- /dev/null +++ b/Luogu/P3605/P3605.cpp @@ -0,0 +1,72 @@ +#include +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1e5 + 5; + +int n, p[N], c[N], ans[N]; +std::vector nums, g[N]; + +inline int lowbit(int x) { + return x & -x; +} + +inline void add(int x, int y) { + for (; x <= n; x += lowbit(x)) c[x] += y; +} + +inline int sum(int x) { + int res = 0; + for (; x; x -= lowbit(x)) res += c[x]; + return res; +} + +void dfs(int u) { + ans[u] -= sum(n) - sum(p[u]); + + for (int v : g[u]) { + dfs(v); + } + + ans[u] += sum(n) - sum(p[u]); + + add(p[u], 1); +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n; + + for (int i = 1; i <= n; i++) { + cin >> p[i]; + + nums.emplace_back(p[i]); + } + + std::sort(nums.begin(), nums.end()); + nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); + + for (int i = 1; i <= n; i++) { + p[i] = std::lower_bound(nums.begin(), nums.end(), p[i]) - nums.begin() + 1; + } + + for (int i = 2, x; i <= n; i++) { + cin >> x; + + g[x].emplace_back(i); + } + + dfs(1); + + for (int i = 1; i <= n; i++) { + cout << ans[i] << endl; + } + + return 0; +}