Description
The cows have once again tried to form a startup company, failing to remember from past experience that cows make terrible managers!The cows, conveniently numbered 1…N1…N (1≤N≤100,000), organize the company as a tree, with cow 1 as the president (the root of the tree). Each cow except the president has a single manager (its "parent" in the tree). Each cow ii has a distinct proficiency rating, p(i), which describes how good she is at her job. If cow ii is an ancestor (e.g., a manager of a manager of a manager) of cow jj, then we say jj is a subordinate of ii.
Unfortunately, the cows find that it is often the case that a manager has less proficiency than seve
ral of her subordinates, in which case the manager should consider promoting some of her subordinate
s. Your task is to help the cows figure out when this is happening. For each cow ii in the company,
please count the number of subordinates jj where p(j)>p(i).
n只奶牛构成了一个树形的公司,每个奶牛有一个能力值pi,1号奶牛为树根。
问对于每个奶牛来说,它的子树中有几个能力值比它大的。
Input
The first line of input contains N
The next N lines of input contain the proficiency ratings p(1)…p(N)
for the cows. Each is a distinct integer in the range 1…1,000,000,000
The next N-1 lines describe the manager (parent) for cows 2…N
Recall that cow 1 has no manager, being the president.
n,表示有几只奶牛 n<=100000
接下来n行为1-n号奶牛的能力值pi
接下来n-1行为2-n号奶牛的经理(树中的父亲)
Output
Please print N lines of output. The ith line of output should tell the number of
subordinates of cow ii with higher proficiency than cow i.
共n行,每行输出奶牛i的下属中有几个能力值比i大
Sample Input
5
804289384
846930887
681692778
714636916
957747794
1
1
2
3
Sample Output
2
0
1
0
0
题目分析
dfs序是个好东西 但是不太会用
这道题直接树状数组+dfs序就可以了
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;
int n;
int head[100100],to[100100*2],net[100100*2];
struct your
{
long long val;
int id;
}a[100100];
int tot;
void add(int x,int y)
{
net[++tot]=head[x];
head[x]=tot;
to[tot]=y;
}
int in[100100],out[100100];
int cnt;
void dfs(int x)
{
in[x]=++cnt;
for(int i=head[x];i;i=net[i])
dfs(to[i]);
out[x]=cnt;
}
int cmp(your j,your k)
{
return j.val>k.val;
}
int ans[100100],f[100100];
int ask(int x)
{
long long sum=0;
for(;x<=n;x+=x&-x) sum+=f[x];
return sum;
}
void update(int x)
{
for(;x;x-=x&-x) f[x]++;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i].val),a[i].id=i;
for(int x,i=2;i<=n;i++)
scanf("%d",&x),add(x,i);
dfs(1);
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
{
ans[a[i].id]=ask(in[a[i].id])-ask(out[a[i].id]+1);
update(in[a[i].id]);
}
for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
return 0;
}