結果

問題 No.778 クリスマスツリー
ユーザー kk
提出日時 2020-09-05 04:17:02
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 78 ms / 2,000 ms
コード長 1,079 bytes
コンパイル時間 1,903 ms
コンパイル使用メモリ 202,104 KB
実行使用メモリ 34,412 KB
最終ジャッジ日時 2023-08-18 03:48:47
合計ジャッジ時間 4,222 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
8,088 KB
testcase_01 AC 4 ms
8,200 KB
testcase_02 AC 4 ms
8,088 KB
testcase_03 AC 4 ms
8,028 KB
testcase_04 AC 4 ms
8,200 KB
testcase_05 AC 4 ms
8,124 KB
testcase_06 AC 57 ms
34,316 KB
testcase_07 AC 25 ms
10,008 KB
testcase_08 AC 78 ms
21,724 KB
testcase_09 AC 69 ms
12,400 KB
testcase_10 AC 65 ms
12,504 KB
testcase_11 AC 67 ms
12,468 KB
testcase_12 AC 64 ms
12,404 KB
testcase_13 AC 40 ms
12,404 KB
testcase_14 AC 57 ms
34,412 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

#define REP(i,n) for(int i=0; i<(int)(n); i++)

template <typename T>
class BIT {
  vector<T> bit;
public:
  BIT() {}
  // manage data in [1, n]
  BIT(int n) : bit(n + 1) {}
  
  void init() {
    fill(bit.begin(), bit.end(), 0);
  }
  
  // return sum in [1, i]
  T sum(int i){
    T s = 0;
    while(i > 0){
      s += bit[i];
      i -= i & -i;
    }
    return s;
  }
  
  // return sum in [l, r]
  T sum(int l, int r) {
    return sum(r) - sum(l-1);
  }
  
  void add(int i, T x){
    while(i < (int)bit.size()){
      bit[i] += x;
      i += i & -i;
    }
  }
};

int n;
vector<int> edges[200000+1];

long long dfs(int v, BIT<long long> &bit) {
  long long ret = bit.sum(v);
  bit.add(v, 1);
  for (int w: edges[v]) {
    ret += dfs(w, bit);
  }
  bit.add(v, -1);
  return ret;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);

  cin >> n;
  for (int i = 1; i < n; i++) {
    int par;
    cin >> par;
    edges[par+1].push_back(i+1);
  }

  BIT<long long> bit(n);
  cout << dfs(1, bit) << endl;
  
  return 0;
}
0