結果

問題 No.778 クリスマスツリー
ユーザー siman
提出日時 2022-03-20 04:14:08
言語 C++17(clang)
(17.0.6 + boost 1.87.0)
結果
AC  
実行時間 105 ms / 2,000 ms
コード長 1,065 bytes
コンパイル時間 2,397 ms
コンパイル使用メモリ 142,320 KB
実行使用メモリ 24,988 KB
最終ジャッジ日時 2024-10-05 20:11:00
合計ジャッジ時間 4,444 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 12
権限があれば一括ダウンロードができます

ソースコード

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