結果

問題 No.872 All Tree Path
ユーザー ゆにぽけゆにぽけ
提出日時 2023-10-15 12:23:31
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 165 ms / 3,000 ms
コード長 1,087 bytes
コンパイル時間 1,239 ms
コンパイル使用メモリ 127,960 KB
実行使用メモリ 33,932 KB
最終ジャッジ日時 2023-10-15 12:23:36
合計ジャッジ時間 4,264 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 121 ms
19,156 KB
testcase_01 AC 165 ms
19,152 KB
testcase_02 AC 123 ms
19,184 KB
testcase_03 AC 89 ms
33,932 KB
testcase_04 AC 3 ms
9,684 KB
testcase_05 AC 124 ms
19,292 KB
testcase_06 AC 115 ms
19,236 KB
testcase_07 AC 120 ms
19,356 KB
testcase_08 AC 12 ms
10,596 KB
testcase_09 AC 12 ms
10,496 KB
testcase_10 AC 12 ms
10,600 KB
testcase_11 AC 12 ms
10,508 KB
testcase_12 AC 11 ms
10,616 KB
testcase_13 AC 3 ms
9,712 KB
testcase_14 AC 3 ms
9,508 KB
testcase_15 AC 3 ms
9,572 KB
testcase_16 AC 3 ms
9,512 KB
testcase_17 AC 4 ms
9,580 KB
testcase_18 AC 3 ms
9,724 KB
testcase_19 AC 3 ms
9,568 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<cassert>
#include<cmath>
#include<ctime>
#include<iomanip>
#include<numeric>
#include<stack>
#include<queue>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<bitset>
#include<random>
using namespace std;
int N,ch[2 << 17];
vector<pair<int,int>> G[2 << 17];
long long dp[2 << 17];
void dfs0(int u,int p,long long W)
{
	dp[u] = W;
	ch[u] = 1;
	for(auto [v,w] : G[u]) if(v != p)
	{
		dfs0(v,u,W+w);
		dp[u] += dp[v];
		ch[u] += ch[v];
	}
}
long long ans;
void dfs1(int u,int p,int W)
{
	if(p >= 0) dp[u] += (dp[p]-dp[u]+(long long)W*(N-2*ch[u]));
	ans += dp[u];
	for(auto [v,w]:G[u]) if(v != p) dfs1(v,u,w);
}
void solve()
{
	cin >> N;
	for(int i = 1;i < N;i++)
	{
		int u,v,w;
		cin >> u >> v >> w;
		u--; v--;
		G[u].push_back(make_pair(v,w));
		G[v].push_back(make_pair(u,w));
	}
	dfs0(0,-1,0);
	ans = 0;
	dfs1(0,-1,0);
	cout << ans << endl;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	//tanosimu
	int tt = 1;
	//cin >> tt;
	while(tt--) solve();
}
0