結果

問題 No.399 動的な領主
ユーザー pekempeypekempey
提出日時 2016-07-15 23:10:34
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 171 ms / 2,000 ms
コード長 1,744 bytes
コンパイル時間 1,198 ms
コンパイル使用メモリ 151,340 KB
実行使用メモリ 30,004 KB
最終ジャッジ日時 2023-08-07 14:58:51
合計ジャッジ時間 3,880 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
5,832 KB
testcase_01 AC 3 ms
5,788 KB
testcase_02 AC 3 ms
5,792 KB
testcase_03 AC 3 ms
5,776 KB
testcase_04 AC 4 ms
6,024 KB
testcase_05 AC 13 ms
7,400 KB
testcase_06 AC 167 ms
24,420 KB
testcase_07 AC 171 ms
24,368 KB
testcase_08 AC 160 ms
24,392 KB
testcase_09 AC 156 ms
24,540 KB
testcase_10 AC 4 ms
6,052 KB
testcase_11 AC 11 ms
7,588 KB
testcase_12 AC 109 ms
24,736 KB
testcase_13 AC 108 ms
24,568 KB
testcase_14 AC 80 ms
29,824 KB
testcase_15 AC 90 ms
30,004 KB
testcase_16 AC 95 ms
26,332 KB
testcase_17 AC 157 ms
24,292 KB
testcase_18 AC 156 ms
24,424 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

class LCA {
public:
	LCA(int n) : g(n), parent(21, vector<int>(n, -1)), depth(n) {}

	void add(int u, int v) {
		g[u].push_back(v);
		g[v].push_back(u);
	}

	void build() {
		dfs(0, -1);
		for (int i = 0; i < 20; i++) {
			for (int j = 0; j < g.size(); j++) {
				if (parent[i][j] != -1) {
					parent[i + 1][j] = parent[i][parent[i][j]];
				}
			}
		}
	}

	int query(int u, int v) {
		if (depth[u] < depth[v]) swap(u, v);
		for (int i = 20; i >= 0; i--) {
			if (depth[u] - depth[v] >= 1 << i) {
				u = parent[i][u];
			}
		}
		if (u == v) return u;
		for (int i = 20; i >= 0; i--) {
			if (parent[i][u] != parent[i][v]) {
				u = parent[i][u];
				v = parent[i][v];
			}
		}
		return parent[0][u];
	}

private:
	vector<vector<int>> g, parent;
	vector<int> depth;

	void dfs(int curr, int prev) {
		parent[0][curr] = prev;
		for (int next : g[curr]) if (next != prev) {
			depth[next] = depth[curr] + 1;
			dfs(next, curr);
		}
	}
};

vector<int> g[101010];
long long imos[101010];
long long part[101010];

void dfs(int curr, int prev) {
	for (int next : g[curr]) if (next != prev) {
		dfs(next, curr);
	}
	if (prev != -1) {
		imos[prev] += imos[curr];
	}
}

int main() {
	int n;
	cin >> n;
	
	LCA lca(n);
	for (int i = 0; i < n - 1; i++) {
		int u, v;
		scanf("%d %d", &u, &v);
		u--;
		v--;
		g[u].push_back(v);
		g[v].push_back(u);
		lca.add(u, v);
	}
	lca.build();

	int Q;
	cin >> Q;
	while (Q--) {
		int u, v;
		scanf("%d %d", &u, &v);
		u--;
		v--;
		int l = lca.query(u, v);

		imos[u]++;
		imos[v]++;
		imos[l] -= 2;
		part[l]++;
	}

	dfs(0, -1);
	long long ans = 0;
	for (int i = 0; i < n; i++) {
		long long v = imos[i] + part[i];
		ans += v * (v + 1) / 2;
	}
	cout << ans << endl;
}
0