結果
| 問題 |
No.898 tri-βutree
|
| コンテスト | |
| ユーザー |
koi_kotya
|
| 提出日時 | 2019-10-05 11:44:59 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 526 ms / 4,000 ms |
| コード長 | 2,566 bytes |
| コンパイル時間 | 2,042 ms |
| コンパイル使用メモリ | 179,976 KB |
| 実行使用メモリ | 31,540 KB |
| 最終ジャッジ日時 | 2024-11-08 22:49:57 |
| 合計ジャッジ時間 | 10,508 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 21 |
ソースコード
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define p_ary(ary,a,b) do { cout << "["; for (int count = (a);count < (b);++count) cout << ary[count] << ((b)-1 == count ? "" : ", "); cout << "]\n"; } while(0)
#define p_map(map,it) do {cout << "{";for (auto (it) = map.begin();;++(it)) {if ((it) == map.end()) {cout << "}\n";break;}else cout << "" << (it)->first << "=>" << (it)->second << ", ";}}while(0)
void dfs(vector<vector<int>>& anc,vector<vector<P>>& G,vector<int>& depth,vector<ll>& dist,int i,int p = -1) {
for (P& e : G[i]) if (e.first != p) {
anc[e.first].push_back(i);
depth[e.first] = depth[i]+1;
dist[e.first] = dist[i]+e.second;
dfs(anc,G,depth,dist,e.first,i);
}
}
void init(vector<vector<int>>& anc,vector<vector<P>>& G,vector<int>& depth,vector<ll>& dist,int k) {
depth[k] = 0;
dist[k] = 0;
dfs(anc,G,depth,dist,k);
int n = anc.size();
for (int i = 0;i < 20;++i) {
for (int j = 0;j < n;++j) {
if (anc[j].size() < i+1 || anc[anc[j][i]].size() < i+1) continue;
anc[j].push_back(anc[anc[j][i]][i]);
}
}
}
int lca(vector<vector<int>>& anc,vector<int>& depth,vector<ll>& dist,int i,int j) {
if (depth[i] > depth[j]) swap(i,j);
while (depth[i] < depth[j]) {
for (int k = anc[j].size()-1;k >= 0;--k) if (depth[anc[j][k]] >= depth[i]) {
j = anc[j][k];
break;
}
}
while (i != j) {
for (int k = anc[i].size()-1;k >= 0;--k) {
if (anc[i][k] != anc[j][k]) {
i = anc[i][k];
j = anc[j][k];
break;
} else if (k == 0) {
i = j = anc[i][0];
}
}
}
return i;
}
ll calc_dist(vector<vector<int>>& anc,vector<int>& depth,vector<ll>& dist,int i,int j) {
return dist[i]+dist[j]-dist[lca(anc,depth,dist,i,j)]*2;
}
int main() {
int n;
cin >> n;
vector<vector<P>> edges(n);
vector<vector<int>> anc(n);
vector<int> depth(n);
vector<ll> dist(n,1LL<<60);
for (int i = 0;i < n-1;++i) {
int u,v,w;
cin >> u >> v >> w;
edges[u].push_back(P(v,w));
edges[v].push_back(P(u,w));
}
init(anc,edges,depth,dist,0);
int q;
cin >> q;
for (int i = 0;i < q;++i) {
int x,y,z;
cin >> x >> y >> z;
cout << (calc_dist(anc,depth,dist,x,y)+calc_dist(anc,depth,dist,y,z)+calc_dist(anc,depth,dist,z,x))/2 << "\n";
}
// p_ary(dist,0,n);
return 0;
}
koi_kotya