結果

問題 No.778 クリスマスツリー
ユーザー simansiman
提出日時 2022-03-20 04:14:08
言語 C++17(clang)
(17.0.6 + boost 1.83.0)
結果
AC  
実行時間 156 ms / 2,000 ms
コード長 1,065 bytes
コンパイル時間 5,493 ms
コンパイル使用メモリ 141,184 KB
実行使用メモリ 25,240 KB
最終ジャッジ日時 2024-04-15 18:21:08
合計ジャッジ時間 3,790 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 5 ms
8,040 KB
testcase_01 AC 4 ms
8,128 KB
testcase_02 AC 4 ms
8,064 KB
testcase_03 AC 5 ms
8,064 KB
testcase_04 AC 4 ms
8,320 KB
testcase_05 AC 5 ms
7,992 KB
testcase_06 AC 97 ms
25,240 KB
testcase_07 AC 47 ms
11,332 KB
testcase_08 AC 156 ms
17,108 KB
testcase_09 AC 149 ms
12,700 KB
testcase_10 AC 152 ms
12,696 KB
testcase_11 AC 147 ms
12,692 KB
testcase_12 AC 144 ms
12,824 KB
testcase_13 AC 84 ms
12,564 KB
testcase_14 AC 96 ms
25,108 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cassert>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <map>
#include <queue>
#include <string.h>
#include <vector>

using namespace std;
typedef long long ll;

class BinaryIndexTree {
public:
  vector <ll> bit;
  int N;

  BinaryIndexTree(int n) {
    N = n;

    for (int i = 0; i <= N; ++i) {
      bit.push_back(0);
    }
  }

  ll sum(int i) {
    ll ret = 0;

    while (i > 0) {
      ret += bit[i];
      i -= i & -i;
    }

    return ret;
  }

  void add(int i, ll x) {
    while (i <= N) {
      bit[i] += x;
      i += i & -i;
    }
  }
};

vector<int> E[200010];

ll dfs(int v, BinaryIndexTree &bit) {
  ll ans = 0;
  bit.add(v, 1);
  if (v > 0) {
    ans += bit.sum(v - 1);
  }

  for (int u : E[v]) {
    ans += dfs(u, bit);
  }

  bit.add(v, -1);
  return ans;
}

int main() {
  int N;
  ll ans = 0;
  cin >> N;

  BinaryIndexTree bit(N + 2);
  for (int i = 2; i <= N; ++i) {
    int a;
    cin >> a;
    E[a + 1].push_back(i);
  }

  cout << dfs(1, bit) << endl;

  return 0;
}
0