結果

問題 No.778 クリスマスツリー
ユーザー finefine
提出日時 2018-12-27 17:46:17
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 113 ms / 2,000 ms
コード長 845 bytes
コンパイル時間 1,632 ms
コンパイル使用メモリ 169,612 KB
実行使用メモリ 31,336 KB
最終ジャッジ日時 2024-04-22 03:04:01
合計ジャッジ時間 3,080 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 2 ms
6,944 KB
testcase_02 AC 2 ms
6,940 KB
testcase_03 AC 2 ms
6,940 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 2 ms
6,940 KB
testcase_06 AC 58 ms
31,336 KB
testcase_07 AC 25 ms
10,292 KB
testcase_08 AC 113 ms
20,556 KB
testcase_09 AC 98 ms
12,712 KB
testcase_10 AC 91 ms
12,576 KB
testcase_11 AC 98 ms
12,656 KB
testcase_12 AC 93 ms
12,688 KB
testcase_13 AC 42 ms
12,444 KB
testcase_14 AC 57 ms
31,316 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

//1-indexであることに注意
template <typename T>
struct BIT {
	int n;
	vector<T> data;

	BIT(int n) : n(n), data(n + 1, 0) {}

	T sum(int i) {
		T s = 0;
		while (i > 0) {
			s += data[i];
			i -= i & -i;
		}
		return s;
	}

	void add(int i, T x) {
		while (i <= n) {
			data[i] += x;
			i += i & -i;
		}
	}
};

void solve(int cur, vector< vector<int> >& g, ll& ans, BIT<ll>& b) {
	ans += b.sum(cur + 1);
	b.add(cur + 1, 1);
	for (int nex : g[cur]) {
		solve(nex, g, ans, b);
	}
	b.add(cur + 1, -1);
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n;
	cin >> n;
	vector< vector<int> > g(n);
	for (int i = 1; i < n; i++) {
		int a;
		cin >> a;
		g[a].push_back(i);
	}
	ll ans = 0;
	BIT<ll> b(n);
	solve(0, g, ans, b);
	cout << ans << endl;
	return 0;
}
0