前言
巨佬说:要有线段树,结果蒟蒻打了一棵...
想想啊,奶牛都开公司当老板了,我还在这里码代码,太失败了。题解
刚看到这道题的时候竟然没有想到深搜,然后仔细一想,发现果然要用深搜。
代码
#include#include #define ll long longusing namespace std;ll read(){ ll x = 0; int zf = 1; char ch = ' '; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar(); if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}struct Edge{ int to, next;} edges[200005];int head[100005], edge_num = 0;void addEdge(int from, int to){ edges[++edge_num] = (Edge){to, head[from]}; head[from] = edge_num;}int n;namespace FenTree{ #define lowbit(x) (x&-x) int BIT[100005]; int query(int i){ int res = 0; for ( ; i; i -= lowbit(i)) res += BIT[i]; return res; } void add(int i){ for ( ; i <= n; i += lowbit(i)) ++BIT[i]; } #undef lowbit};using namespace FenTree;int p[100005], dy[100005];int ans[100005];bool Comp(const int &a, const int &b){return p[a] > p[b];};void DFS(int u, int fa){ ans[u] -= query(p[u]); for (int c_e = head[u]; c_e; c_e = edges[c_e].next) if (edges[c_e].to != fa) DFS(edges[c_e].to, u); ans[u] += query(p[u]); add(p[u]);}int main(){ n = read(); for (int i = 1; i <= n; ++i) p[i] = read(), dy[i] = i; sort(dy + 1, dy + n + 1, Comp); for (int i = 1; i <= n; ++i) p[dy[i]] = i; for (int i = 2; i <= n; ++i){int x = read(); addEdge(i, x), addEdge(x, i);} DFS(1, 1); for (int i = 1; i <= n; ++i) printf("%d\n", ans[i]); return 0;}