結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー Example0911Example0911
提出日時 2021-03-17 14:22:50
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 49 ms / 2,000 ms
コード長 663 bytes
コンパイル時間 1,985 ms
コンパイル使用メモリ 198,524 KB
最終ジャッジ日時 2025-01-19 17:54:46
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

#include "bits/stdc++.h"


using namespace std;
using ll = long long;
using P = pair<ll, ll>;
const ll INF = (1LL << 61);
ll mod = 998244353;

int N;
vector<ll>sz;
ll ans = 0;
void dfs(vector<vector<int>> &G, int v, int p) {
	for (auto nv : G[v]) {
		if (nv == p)continue;
		dfs(G, nv, v);
		ans += (N - sz[nv])*sz[nv];
		sz[v] += sz[nv];
	}
	ans += N;
	ans += (N - sz[v])*sz[v];
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> N;
	vector<vector<int>>G(N);
	for (int i = 0; i < N - 1; i++) {
		int A, B; cin >> A >> B; A--; B--;
		G[A].push_back(B);
		G[B].push_back(A);
	}
	sz.resize(N, 1);
	dfs(G, 0, -1);
	cout << ans << endl;
	return 0;
}
0