結果

問題 No.898 tri-βutree
ユーザー IKyoproIKyopro
提出日時 2019-10-04 23:58:57
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 506 ms / 4,000 ms
コード長 1,865 bytes
コンパイル時間 1,529 ms
コンパイル使用メモリ 82,676 KB
実行使用メモリ 34,056 KB
最終ジャッジ日時 2023-08-08 16:09:34
合計ジャッジ時間 11,742 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 296 ms
34,056 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 488 ms
26,664 KB
testcase_08 AC 485 ms
26,704 KB
testcase_09 AC 488 ms
26,644 KB
testcase_10 AC 494 ms
26,856 KB
testcase_11 AC 489 ms
26,504 KB
testcase_12 AC 490 ms
26,652 KB
testcase_13 AC 492 ms
26,592 KB
testcase_14 AC 499 ms
26,568 KB
testcase_15 AC 494 ms
26,664 KB
testcase_16 AC 506 ms
26,488 KB
testcase_17 AC 494 ms
26,644 KB
testcase_18 AC 486 ms
26,564 KB
testcase_19 AC 495 ms
26,500 KB
testcase_20 AC 493 ms
26,500 KB
testcase_21 AC 496 ms
26,592 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
typedef long long ll;

struct edge{
    int to;
    ll w;
};

class LCA{
private:
	vector<vector<edge>> v;
	vector<vector<int>> parent;
	vector<int> depth;
	void dfs(int n,int m,int d){
		parent[0][n] = m;
		depth[n] = d;
		for(auto x:v[n]){
			if(x.to!=m) dfs(x.to,n,d+1);
		}
	}
public:
	LCA(int N,int root,vector<vector<edge>>& tree){
		v = tree;
		parent = vector<vector<int>>(20,vector<int>(N,0));
		depth = vector<int>(N,0);
		dfs(root,-1,0);
		for(int j=0;j+1<20;j++){
			for(int i=0;i<N;i++){
				if(parent[j][i]<0) parent[j+1][i] = -1;
				else parent[j+1][i] = parent[j][parent[j][i]];
			}
		}
	}
	int lca(int n,int m){
		if(depth[n]>depth[m]) swap(n,m);
		for(int j=0;j<20;j++){
			if((depth[m]-depth[n]) >> j&1) m = parent[j][m];
		}
		if(n==m) return n;
		for(int j=19;j>=0;j--){
			if(parent[j][n]!=parent[j][m]){
				n = parent[j][n];
				m = parent[j][m];
			}
		}
		return parent[0][n];
	}
	int dep(int n){return depth[n];}
};


int main(){
    int N;
    cin >> N;
    vector<vector<edge>> tree(N);
    for(int i=0;i<N-1;i++){
        int a,b;
        ll w;
        cin >> a >> b >> w;
        tree[a].push_back({b,w});
        tree[b].push_back({a,w});
    }
    LCA lca(N,0,tree);
    vector<ll> dist(N,0);
    function<void(int,int)> dfs = [&](int cur,int par){
        for(auto x:tree[cur]) if(par!=x.to) {
            dist[x.to] = dist[cur] + x.w;
            dfs(x.to,cur);
        }
    };
    dfs(0,-1);
    int Q;
    cin >> Q;
    auto ans = [&](int x,int y,int z){
        ll res = 2*(dist[x]+dist[y]+dist[z]);
        res -= 2*(dist[lca.lca(x,y)]+dist[lca.lca(y,z)]+dist[lca.lca(z,x)]);
        return res/2;
    };
    for(int i=0;i<Q;i++){
        int x,y,z;
        cin >> x >> y >> z;
        cout << ans(x,y,z) << endl;
    }
}
0