結果
| 問題 | No.872 All Tree Path | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2019-06-15 16:28:42 | 
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 222 ms / 3,000 ms | 
| コード長 | 1,176 bytes | 
| コンパイル時間 | 1,582 ms | 
| コンパイル使用メモリ | 169,328 KB | 
| 実行使用メモリ | 37,504 KB | 
| 最終ジャッジ日時 | 2024-11-19 00:13:57 | 
| 合計ジャッジ時間 | 5,226 ms | 
| ジャッジサーバーID (参考情報) | judge3 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 2 | 
| other | AC * 18 | 
ソースコード
#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(2 <= N && N <= 200000);
	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 <= 100);
		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;
}
            
            
            
        