結果

問題 No.872 All Tree Path
ユーザー ningenMeningenMe
提出日時 2019-08-30 00:04:24
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 254 ms / 3,000 ms
コード長 1,793 bytes
コンパイル時間 1,881 ms
コンパイル使用メモリ 179,736 KB
実行使用メモリ 38,396 KB
最終ジャッジ日時 2024-04-28 21:27:14
合計ジャッジ時間 4,881 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 221 ms
23,424 KB
testcase_01 AC 242 ms
23,552 KB
testcase_02 AC 236 ms
23,648 KB
testcase_03 AC 102 ms
38,396 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 254 ms
23,548 KB
testcase_06 AC 246 ms
23,552 KB
testcase_07 AC 217 ms
23,552 KB
testcase_08 AC 13 ms
5,376 KB
testcase_09 AC 13 ms
5,376 KB
testcase_10 AC 13 ms
5,376 KB
testcase_11 AC 13 ms
5,376 KB
testcase_12 AC 14 ms
5,376 KB
testcase_13 AC 2 ms
5,376 KB
testcase_14 AC 2 ms
5,376 KB
testcase_15 AC 2 ms
5,376 KB
testcase_16 AC 2 ms
5,376 KB
testcase_17 AC 2 ms
5,376 KB
testcase_18 AC 2 ms
5,376 KB
testcase_19 AC 2 ms
5,376 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);
	}
}


//Union Find Tree
class Union_Find_Tree_Size {
public:
	vector<int> parent;

    Union_Find_Tree_Size(int N = 1) : parent(N,-1){
	}
 
	int root(int n) {
        return (parent[n]<0?n:parent[n] = root(parent[n]));
	}

    bool same(int n, int m) {
		return root(n) == root(m);
	}
 
	void unite(int n, int m) {
		n = root(n);
		m = root(m);
		if (n == m) return;
		if(parent[n]>parent[m]) swap(n, m);
        parent[n] += parent[m];
        parent[m] = n;
	}

    int size(int n){
        return (-parent[root(n)]);
    }
};

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);
	Union_Find_Tree_Size uf(N);

	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});
		uf.unite(u,v);
	}
	for(int i = 0; i < N; ++i) assert(uf.size(i)==N);

	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