結果

問題 No.386 貪欲な領主
ユーザー chocoruskchocorusk
提出日時 2019-01-13 11:21:16
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 241 ms / 2,000 ms
コード長 1,475 bytes
コンパイル時間 1,844 ms
コンパイル使用メモリ 95,428 KB
実行使用メモリ 21,500 KB
最終ジャッジ日時 2023-08-26 17:06:21
合計ジャッジ時間 4,159 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
11,568 KB
testcase_01 AC 3 ms
11,676 KB
testcase_02 AC 3 ms
11,700 KB
testcase_03 AC 4 ms
11,540 KB
testcase_04 AC 241 ms
21,500 KB
testcase_05 AC 193 ms
16,968 KB
testcase_06 AC 212 ms
16,788 KB
testcase_07 AC 4 ms
11,532 KB
testcase_08 AC 32 ms
12,056 KB
testcase_09 AC 6 ms
11,700 KB
testcase_10 AC 2 ms
11,624 KB
testcase_11 AC 2 ms
11,628 KB
testcase_12 AC 3 ms
11,616 KB
testcase_13 AC 8 ms
11,784 KB
testcase_14 AC 204 ms
17,028 KB
testcase_15 AC 204 ms
21,436 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
vector<int> g[100000];
int d[100000];
int p[17][100000];
bool used[100000];
ll ct[100000];
void dfs0(int x){
	used[x]=1;
	for(auto y:g[x]){
		if(!used[y]){
			d[y]=d[x]+1;
			ct[y]+=ct[x];
			p[0][y]=x;
			dfs0(y);
		}
	}
}
int lca(int a, int b){
	if(d[a]>d[b]) swap(a, b);
    int a1=a, b1=b;
    int dd=d[b]-d[a], i=0;
    while(dd>0){
        if(dd%2==1){
            b1=p[i][b1];
        }
        dd/=2;
        i++;
    }
    if(a1==b1) return a1;
    for(int i=16; i>=0; i--){
        if(p[i][a1]!=p[i][b1]){
            a1=p[i][a1], b1=p[i][b1];
        }
    }
    return p[0][a1];
}
int main()
{
	int n;
	cin>>n;
	for(int i=0; i<n-1; i++){
		int u, v;
		cin>>u>>v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	for(int i=0; i<n; i++) cin>>ct[i];
	dfs0(0);
	for(int i=1; i<17; i++){
        for(int x=0; x<n; x++){
            p[i][x]=p[i-1][p[i-1][x]];
        }
    }
	int m; cin>>m;
	ll ans=0;
	for(int i=0; i<m; i++){
		int a, b; ll c;
		cin>>a>>b>>c;
		int t=lca(a, b);
		ll s=ct[b]-ct[t]+ct[a];
		if(t>0) s-=ct[p[0][t]];
		ans+=(c*s);
	}
	cout<<ans<<endl;
	return 0;
}
0