結果

問題 No.778 クリスマスツリー
ユーザー goodbatongoodbaton
提出日時 2018-12-25 11:17:23
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 67 ms / 2,000 ms
コード長 1,733 bytes
コンパイル時間 919 ms
コンパイル使用メモリ 103,548 KB
実行使用メモリ 31,672 KB
最終ジャッジ日時 2024-04-22 03:03:58
合計ジャッジ時間 2,179 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
8,512 KB
testcase_01 AC 4 ms
9,672 KB
testcase_02 AC 4 ms
9,284 KB
testcase_03 AC 3 ms
8,268 KB
testcase_04 AC 3 ms
8,644 KB
testcase_05 AC 4 ms
9,152 KB
testcase_06 AC 58 ms
31,672 KB
testcase_07 AC 28 ms
13,636 KB
testcase_08 AC 67 ms
22,224 KB
testcase_09 AC 63 ms
16,092 KB
testcase_10 AC 66 ms
16,092 KB
testcase_11 AC 62 ms
16,080 KB
testcase_12 AC 64 ms
16,084 KB
testcase_13 AC 41 ms
16,016 KB
testcase_14 AC 55 ms
31,580 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

#include <functional>
#include <cassert>

typedef long long ll;
using namespace std;

#ifdef LOCAL
#define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl;
#else
#define debug(x) ;
#endif

#define mod 1000000007 //1e9+7(prime number)
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 200010

/* Binary Indexed Tree(1-index) */

struct BIT{
  typedef int Type;
  int bit_size;
  vector<Type> data;
  
  BIT(int n){
    bit_size = n;
    data.assign(n+2, 0);
  }
  
  //add x to kth value
  void add(int k, Type x){
    k++;
    while(k <= bit_size){
      data[k] += x;
      k += k & (-k);
    }
  }
  
  //sum of [1,k]
  Type query(int k){
    k++;
    Type rec = 0;
    while(k > 0){
      rec += data[k];
      k -= k & (-k);
    }
    return rec;
  }
};

vector<int> tree[SIZE];

vector<int> euler;
int pos_in[SIZE], pos_out[SIZE];

void dfs(int now){
  euler.push_back(now);
  pos_in[now] = euler.size() - 1;
  
  for(int to : tree[now]){
    dfs(to);
  }
  
  euler.push_back(now);
  pos_out[now] = euler.size() - 1;
}

int main(){
  int n;

  scanf("%d", &n);

  for(int i=1;i<n;i++){
    int a;
    scanf("%d", &a);
    tree[a].push_back(i);
  }

  dfs(0);

  BIT bit(n*2);

  ll ans = 0;
  
  for(int i=n-1;i>=0;i--){
    int res = bit.query(pos_out[i]) - bit.query(pos_in[i]);
    ans += res;
    bit.add(pos_in[i], 1);
  }

  cout << ans << endl;
  
  return 0;
}


0