結果
| 問題 |
No.898 tri-βutree
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2019-11-10 00:49:48 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 194 ms / 4,000 ms |
| コード長 | 2,714 bytes |
| コンパイル時間 | 1,911 ms |
| コンパイル使用メモリ | 185,908 KB |
| 実行使用メモリ | 21,984 KB |
| 最終ジャッジ日時 | 2024-11-08 23:09:48 |
| 合計ジャッジ時間 | 6,955 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 21 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, ll>;
struct LCA {
using Graph = vector< vector<P> >;
const Graph& g;
const int LOGV;
const int root;
vector< vector<int> > parent;
vector<int> depth;
vector<ll> weights;
LCA(const Graph& g, int root = 0) : g(g), LOGV(32 - __builtin_clz(g.size())), root(root) {
int V = g.size();
parent.resize(LOGV, vector<int>(V));
depth.resize(V);
weights.resize(V);
dfs(root, -1, 0, 0);
for (int k = 0; k + 1 < LOGV; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0) parent[k + 1][v] = -1;
else parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
void dfs(int v, int p, int d, ll w) {
parent[0][v] = p;
depth[v] = d;
weights[v] = w;
for (const P& e : g[v]) {
if (e.first != p) dfs(e.first, v, d + 1, w + e.second);
}
}
int operator()(int u, int v) const {
if (depth[u] > depth[v]) swap(u, v);
for (int k = 0; k < LOGV; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
}
}
if (u == v) return u;
for (int k = LOGV - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
vector< vector<P> > G(n);
for (int i = 1; i < n; i++) {
int u, v;
ll w;
cin >> u >> v >> w;
G[u].emplace_back(v, w);
G[v].emplace_back(u, w);
}
LCA lca(G);
const vector<int>& depth = lca.depth;
const vector<ll>& weights = lca.weights;
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int x, y, z;
cin >> x >> y >> z;
int xy = lca(x, y);
int yz = lca(y, z);
int zx = lca(z, x);
int tar = xy;
int hoge = lca(xy, z);
ll ans = weights[x] + weights[y] - weights[xy] * 2;
ans += weights[z] + weights[xy] - weights[hoge] * 2;
if (depth[tar] < depth[yz]) {
tar = yz;
ans = weights[y] + weights[z] - weights[yz] * 2;
ans += weights[x] + weights[yz] - weights[hoge] * 2;
}
if (depth[tar] < depth[zx]) {
tar = zx;
ans = weights[z] + weights[x] - weights[zx] * 2;
ans += weights[y] + weights[zx] - weights[hoge] * 2;
}
cout << ans << "\n";
}
return 0;
}