結果
| 問題 |
No.778 クリスマスツリー
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2018-12-25 01:38:12 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 161 ms / 2,000 ms |
| コード長 | 2,070 bytes |
| コンパイル時間 | 2,282 ms |
| コンパイル使用メモリ | 201,008 KB |
| 最終ジャッジ日時 | 2025-01-06 20:01:11 |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 12 |
ソースコード
#include <bits/stdc++.h>
#define show(x) std::cerr << #x << " = " << (x) << std::endl
using ll = long long;
using ull = unsigned long long;
struct Sum
{
using T = ll;
T operator()(const T& a, const T& b) const { return a + b; }
static constexpr T id() { return 0; }
};
constexpr std::size_t PC(ull v) { return v = (v & 0x5555555555555555ULL) + (v >> 1 & 0x5555555555555555ULL), v = (v & 0x3333333333333333ULL) + (v >> 2 & 0x3333333333333333ULL), v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL, static_cast<std::size_t>(v * 0x0101010101010101ULL >> 56 & 0x7f); }
constexpr std::size_t LG(ull v) { return v == 0 ? 0 : (v--, v |= (v >> 1), v |= (v >> 2), v |= (v >> 4), v |= (v >> 8), v |= (v >> 16), v |= (v >> 32), PC(v)); }
constexpr ull SZ(const ull v) { return 1ULL << LG(v); }
class BinaryIndexedTree
{
public:
using T = ll;
BinaryIndexedTree(const std::size_t n) : data_num(n), size(SZ(n)), value(size + 1, 0) {}
void add(const std::size_t a, const T& val)
{
for (std::size_t ind = a + 1; ind <= size; ind += ind & (-ind)) { value[ind] += val; }
}
T accumulate(const std::size_t a) const
{
T sum = 0;
for (std::size_t ind = a + 1; ind != 0; ind &= ind - 1) { sum += value[ind]; }
return sum;
}
T accumulate(const std::size_t l, const std::size_t r) const { return accumulate(r - 1) - (l == 0 ? 0 : accumulate(l - 1)); }
private:
const std::size_t data_num, size;
std::vector<T> value;
};
int main()
{
int N;
std::cin >> N;
std::vector<std::vector<int>> g(N);
for (int i = 1, A; i < N; i++) { std::cin >> A, g[A].push_back(i); }
std::vector<int> l(N), r(N);
int S = 0;
auto dfs = [&](auto&& self, const int s) -> void {
l[s] = S++;
for (const int to : g[s]) { self(self, to); }
r[s] = S++;
};
dfs(dfs, 0);
BinaryIndexedTree bit(S);
ll ans = 0;
for (int i = N - 1; i >= 0; i--) {
bit.add(l[i], 1);
ans += bit.accumulate(l[i] + 1, r[i]);
}
std::cout << ans << std::endl;
return 0;
}