結果

問題 No.872 All Tree Path
ユーザー okok
提出日時 2019-08-30 22:48:30
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 198 ms / 3,000 ms
コード長 1,356 bytes
コンパイル時間 1,307 ms
コンパイル使用メモリ 81,204 KB
実行使用メモリ 32,792 KB
最終ジャッジ日時 2023-08-14 06:54:05
合計ジャッジ時間 4,326 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 186 ms
21,200 KB
testcase_01 AC 198 ms
21,004 KB
testcase_02 AC 184 ms
21,176 KB
testcase_03 AC 91 ms
32,792 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 175 ms
20,972 KB
testcase_06 AC 174 ms
20,912 KB
testcase_07 AC 183 ms
20,856 KB
testcase_08 AC 11 ms
4,824 KB
testcase_09 AC 11 ms
4,956 KB
testcase_10 AC 12 ms
4,964 KB
testcase_11 AC 11 ms
4,956 KB
testcase_12 AC 11 ms
5,116 KB
testcase_13 AC 1 ms
4,384 KB
testcase_14 AC 1 ms
4,384 KB
testcase_15 AC 1 ms
4,380 KB
testcase_16 AC 2 ms
4,380 KB
testcase_17 AC 2 ms
4,380 KB
testcase_18 AC 2 ms
4,384 KB
testcase_19 AC 1 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
#include<vector>
#include<algorithm>

using namespace std;

#define int long long
#define endl "\n"

const long long INF = (long long)1e18;
// const long long MOD = 1'000'000'007; 

string yn(bool f){return f?"Yes":"No";}
string YN(bool f){return f?"YES":"NO";}

int N, result;
vector<vector<pair<int,int>>> tree;
vector<int> con, ans;


void dfs1(int per = -1, int now = 1){
	con[now]++;
	
	for(int i = 0; i < tree[now].size(); i++){
		if(tree[now][i].first == per) continue;
		
		dfs1(now, tree[now][i].first);
		
		con[now] += con[tree[now][i].first];
		ans[now] += ans[tree[now][i].first] + con[tree[now][i].first]*tree[now][i].second;
	}
}

void dfs2(int per = -1, int now = 1, int sum = ans[1]){
	int res = sum;
	
	result += res;

	for(pair<int,int> next : tree[now]){
		if(per == next.first) continue;
		
		dfs2(now, next.first, res + (N - con[next.first])*next.second - (con[next.first])*next.second);
	}
	
}

signed main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);
	
	
	
	cin>>N;
	
	tree.resize(N+1);
	con.resize(N+1);
	ans.resize(N+1);
	
	
	for(int i = 0; i < N-1; i++){
		int u, v, w;
		
		cin>>u>>v>>w;
		
		tree[u].push_back(make_pair(v,w));
		tree[v].push_back(make_pair(u,w));
	}
	
	dfs1();
	dfs2();
	
	cout<<result<<endl;
	
	return 0;
}
0