結果

問題 No.898 tri-βutree
ユーザー kuhaku
提出日時 2019-10-11 20:48:36
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,470 bytes
コンパイル時間 1,639 ms
コンパイル使用メモリ 174,740 KB
実行使用メモリ 29,440 KB
最終ジャッジ日時 2024-11-08 23:05:54
合計ジャッジ時間 12,751 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 1
other TLE * 1 -- * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

#define REP(i, n) for(ll (i) = 0; (i) < (n); (i)++)
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define mp make_pair
#define INF 1e18

typedef long long ll;
typedef pair<ll, ll> P;

#define MAX_N 100000

vector<P> tree[MAX_N];
ll dist[MAX_N], parent[MAX_N], depth[MAX_N];

void dfs(ll n, ll p){
	REP(i, tree[n].size()){
		ll c = tree[n][i].first;
		if(c != p){
			parent[c] = n;
			depth[c] = depth[n]+1;
			dfs(c, n);
		}
	}
}

ll lca(ll a, ll b){
	ll m = a, n = b;
	while(m != n){
		if(depth[m] >= depth[n]) m = parent[m];
		if(depth[n] > depth[m]) n = parent[n];
	}

	return m;
}

int main(void){
	ll n;
	cin >> n;

	fill(dist, dist+n, INF);

	REP(i, n-1){
		ll u, v, w;
		cin >> u >> v >> w;
		tree[u].push_back(mp(v, w));
		tree[v].push_back(mp(u, w));
	}

	depth[0] = 0;
	dfs(0, 0);

	priority_queue<P, vector<P>, greater<P> > que;
	dist[0] = 0;
	que.push(mp(0, 0));
	while(!que.empty()){
		P out = que.top(); que.pop();
		if(out.first > dist[out.second]) continue;
		dist[out.second] = out.first;
		REP(i, tree[out.second].size()){
			P in = tree[out.second][i];
			que.push(mp(out.first+in.second, in.first));
		}
	}

	ll q;
	cin >> q;

	REP(i, q){
		ll x, y, z;
		cin >> x >> y >> z;

		ll ans = 0;
		ans += dist[x]+dist[y]-2*dist[lca(x, y)];
		ans += dist[y]+dist[z]-2*dist[lca(y, z)];
		ans += dist[z]+dist[x]-2*dist[lca(z, x)];

		cout << ans/2 << endl;
	}

	return 0;
}
0