BZOJ4756: [Usaco2017 Jan]Promotion Counting(线段树合并)
程序员文章站
2022-04-15 17:20:21
题意 "题目链接" Sol 线段树合并板子题 cpp include using namespace std; const int MAXN = 400000, SS = MAXN 21; inline int read() { char c = getchar(); int x = 0, f = ......
题意
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; } /* */
上一篇: Django环境配置