Advertisement
4eyes4u

Untitled

Jan 17th, 2017
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N=1e5+10;
  5. const int BIT_SIZE=1e5+5;
  6.  
  7. int a[N];
  8. pair<int, int> p[N];
  9. vector<int> g[N];
  10. int sol[N], t;
  11. int bit[BIT_SIZE];
  12. int lson[N], rson[N];
  13. int n;
  14.  
  15. struct Query
  16. {
  17.     int pos, type, val, idx;
  18.     bool operator<(const Query &qv) const
  19.     {
  20.         if (pos==qv.pos) return type<qv.type;
  21.         return pos<qv.pos;
  22.     }
  23. };
  24.  
  25. vector<Query> q;
  26.  
  27. void update (int x, int val)
  28. {
  29.     while (x<=BIT_SIZE)
  30.     {
  31.         bit[x]+=val;
  32.         x+=x&-x;
  33.     }
  34. }
  35.  
  36. int get (int x)
  37. {
  38.     int ret=0;
  39.     while (x>0)
  40.     {
  41.         ret+=bit[x];
  42.         x-=x&-x;
  43.     }
  44.     return ret;
  45. }
  46.  
  47. void compress ()
  48. {
  49.     sort (p+1, p+n+1);
  50.     int last=0, k=0;
  51.     for (int i=1;i<=n;i++)
  52.     {
  53.         if (p[i].first==last) a[p[i].second]=k;
  54.         else a[p[i].second]=++k;
  55.         last=p[i].first;
  56.     }
  57. }
  58.  
  59. int dfs (int v, int prev)
  60. {
  61.     lson[v]=rson[v]=++t;
  62.     q.push_back({lson[v], 1, a[v], 0});
  63.     for (auto xt: g[v])
  64.     {
  65.         if (xt==prev) continue;
  66.         rson[v]=dfs(xt, v);
  67.     }
  68.     return rson[v];
  69. }
  70.  
  71. int main()
  72. {
  73.     freopen("promote.in", "r", stdin);
  74.     freopen("promote.out", "w", stdout);
  75.  
  76.     scanf ("%d", &n);
  77.     for (int i=1;i<=n;i++)
  78.     {
  79.         scanf ("%d", &a[i]);
  80.         p[i]=make_pair(a[i], i);
  81.     }
  82.  
  83.     compress();
  84.  
  85.     for (int i=2;i<=n;i++)
  86.     {
  87.         int x;
  88.         scanf ("%d", &x);
  89.         g[i].push_back(x);
  90.         g[x].push_back(i);
  91.     }
  92.  
  93.     dfs (1, 0);
  94.  
  95.     for (int i=1;i<=n;i++)
  96.     {
  97.         q.push_back({lson[i], 0, a[i], i});
  98.         q.push_back({rson[i], 2, a[i], i});
  99.     }
  100.  
  101.     sort (q.begin(), q.end());
  102.     for (int i=0;i<q.size();i++)
  103.     {
  104.         Query xt=q[i];
  105.         if (xt.type==1) update (xt.val, 1);
  106.         if (xt.type==0) sol[xt.idx]-=get(xt.val);
  107.         if (xt.type==2) sol[xt.idx]+=get(xt.val);
  108.     }
  109.  
  110.     for (int i=1;i<=n;i++) printf ("%d\n", rson[i]-lson[i]+1-sol[i]);
  111.  
  112.     return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement