結果

問題 No.778 クリスマスツリー
ユーザー SSRSSSRS
提出日時 2022-04-23 16:12:27
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 92 ms / 2,000 ms
コード長 1,020 bytes
コンパイル時間 2,188 ms
コンパイル使用メモリ 204,396 KB
実行使用メモリ 32,852 KB
最終ジャッジ日時 2023-09-07 09:00:08
合計ジャッジ時間 4,449 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 83 ms
32,804 KB
testcase_07 AC 35 ms
11,576 KB
testcase_08 AC 87 ms
21,708 KB
testcase_09 AC 80 ms
14,044 KB
testcase_10 AC 80 ms
14,044 KB
testcase_11 AC 92 ms
14,072 KB
testcase_12 AC 74 ms
14,008 KB
testcase_13 AC 60 ms
14,044 KB
testcase_14 AC 80 ms
32,852 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
void dfs(vector<vector<int>> &c, vector<int> &L, vector<int> &R, int &t, int v = 0){
  L[v] = t;
  t++;
  for (int w : c[v]){
    dfs(c, L, R, t, w);
  }
  R[v] = t;
}
struct binary_indexed_tree{
  int N;
  vector<int> BIT;
  binary_indexed_tree(int N): N(N), BIT(N + 1, 0){
  }
  void add(int i){
    i++;
    while (i <= N){
      BIT[i]++;
      i += i & -i;
    }
  }
  int sum(int i){
    int ans = 0;
    while (i > 0){
      ans += BIT[i];
      i -= i & -i;
    }
    return ans;
  }
  int sum(int L, int R){
    return sum(R) - sum(L);
  }
};
int main(){
  int N;
  cin >> N;
  vector<int> A(N, -1);
  for (int i = 1; i < N; i++){
    cin >> A[i];
  }
  vector<vector<int>> c(N);
  for (int i = 1; i < N; i++){
    c[A[i]].push_back(i);
  }
  vector<int> L(N), R(N);
  int t = 0;
  dfs(c, L, R, t);
  binary_indexed_tree BIT(N);
  long long ans = 0;
  for (int i = N - 1; i >= 0; i--){
    ans += BIT.sum(L[i], R[i]);
    BIT.add(L[i]);
  }
  cout << ans << endl;
}
0