結果

問題 No.872 All Tree Path
ユーザー ningenMeningenMe
提出日時 2019-06-15 02:03:48
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 186 ms / 3,000 ms
コード長 1,181 bytes
コンパイル時間 1,382 ms
コンパイル使用メモリ 171,448 KB
実行使用メモリ 37,588 KB
最終ジャッジ日時 2024-04-27 17:24:55
合計ジャッジ時間 4,442 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 181 ms
22,808 KB
testcase_01 AC 186 ms
22,616 KB
testcase_02 AC 171 ms
22,784 KB
testcase_03 AC 98 ms
37,588 KB
testcase_04 AC 2 ms
6,944 KB
testcase_05 AC 180 ms
22,628 KB
testcase_06 AC 179 ms
22,692 KB
testcase_07 AC 175 ms
22,644 KB
testcase_08 AC 12 ms
6,940 KB
testcase_09 AC 12 ms
6,944 KB
testcase_10 AC 12 ms
6,940 KB
testcase_11 AC 12 ms
6,940 KB
testcase_12 AC 12 ms
6,940 KB
testcase_13 AC 2 ms
6,940 KB
testcase_14 AC 1 ms
6,944 KB
testcase_15 AC 1 ms
6,940 KB
testcase_16 AC 1 ms
6,940 KB
testcase_17 AC 1 ms
6,940 KB
testcase_18 AC 1 ms
6,944 KB
testcase_19 AC 2 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

long long N; 
vector<vector<pair<int,long long>>> edge;
vector<long long> dist,sum,scale;
int idx = 0;

void dfs1(int from, int prev = -1){
	for(int i = 0; i < edge[from].size(); ++i){
		int to = edge[from][i].first;
		if(to==prev) continue;
		dist[to] = dist[from] + edge[from][i].second;
		dfs1(to,from);
		scale[from] += scale[to];
	}
}

void dfs2(int from, int prev = -1){
	for(int i = 0; i < edge[from].size(); ++i){
		int to = edge[from][i].first;
		if(to==prev) continue;
		sum[to] = sum[from] + (N - 2*scale[to])*edge[from][i].second;
		dfs2(to,from);
	}
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	cin >> N;
	assert(1 <= N && N <= 300000);
	edge.resize(N);
	dist.resize(N);
	sum.resize(N);
	scale.resize(N,1);

	for(int i = 0; i < N-1; ++i){
		int u,v;
		long long w;
		cin >> u >> v >> w;
		assert(1 <= u && u <= N);
		assert(1 <= v && v <= N);
		assert(1 <= w && w <= 10000000);
		u--,v--;
		edge[u].push_back({v,w});
		edge[v].push_back({u,w});
	}

	dist[0] = 0;
	dfs1(0);
	sum[0] = accumulate(dist.begin(),dist.end(),0LL);
	dfs2(0);
	cout << accumulate(sum.begin(),sum.end(),0LL) << endl;
    return 0;
}
0