結果

問題 No.778 クリスマスツリー
ユーザー tonetone
提出日時 2019-07-27 02:56:25
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 260 ms / 2,000 ms
コード長 1,485 bytes
コンパイル時間 625 ms
コンパイル使用メモリ 74,120 KB
実行使用メモリ 27,848 KB
最終ジャッジ日時 2024-04-22 03:08:50
合計ジャッジ時間 3,170 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 6 ms
10,100 KB
testcase_01 AC 5 ms
10,112 KB
testcase_02 AC 6 ms
10,112 KB
testcase_03 AC 5 ms
10,240 KB
testcase_04 AC 6 ms
10,272 KB
testcase_05 AC 6 ms
10,156 KB
testcase_06 AC 137 ms
27,848 KB
testcase_07 AC 93 ms
19,264 KB
testcase_08 AC 260 ms
23,108 KB
testcase_09 AC 245 ms
18,636 KB
testcase_10 AC 236 ms
18,624 KB
testcase_11 AC 249 ms
18,760 KB
testcase_12 AC 234 ms
18,624 KB
testcase_13 AC 131 ms
18,500 KB
testcase_14 AC 139 ms
27,844 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

//https://yukicoder.me/problems/no/778
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <bitset>
#include <tuple>
#include <set>
#include <map>
#define range(i, r) for(int i=0;i<r;i++)
#define ranges(i, l, r) for(int i=l;i<r;i++)
#define vv(a, b, c, d) vector<vector<d> >(a, vector<d>(b, c))
#define vvi std::vector<std::vector<int> >
#define vvl std::vector<std::vector<ll> >
#define MODs 1000000007;
#define MODn 1000000009;
typedef long long int ll;
using namespace std;

ll ans=0;
int M=1;
vvi num = vv(300000,0,0,int);
std::vector<int> bit;
void init(int N){
  while(M<N) M*=2;
  M= M*2-1;
  for(int i=0;i<M;i++) bit.push_back(0);
}
void add(int a, int k){
  k += (M+1)/2-1;
  bit[k]+=a;
  while(k>0){
    k=(k-1)/2;
    bit[k]=bit[k*2+1]+bit[k*2+2];
  }
}
int query(int a, int b, int l, int r, int k){
  if(r<=a||b<=l) return 0;
  if(a<=l && r<=b) return bit[k];
  int A = query(a, b, l, (l+r)/2, k*2+1);
  int B = query(a, b, (l+r)/2, r, k*2+2);
  return A+B;
}

void dfs(int cu, int pa=-1){
  //std::cout << cu << '\n';
  ans += query(0, cu+1, 0, (M+1)/2, 0);
  add(1, cu);
  for(int i=0;i<num[cu].size();i++) if(num[cu][i]!=pa) dfs(num[cu][i], cu);
  add(-1, cu);
}

int main(int argc, char const *argv[]) {
  int N;
  std::cin >> N;
  init(N);
  for(int i=1;i<N;i++){
    int a;
    std::cin >> a;
    num[i].push_back(a);
    num[a].push_back(i);
  }
  dfs(0);
  std::cout << ans << '\n';
  return 0;
}
0