Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cstring>
- #include <algorithm>
- #include <cmath>
- #include <vector>
- #include <set>
- #include <map>
- #include <stack>
- #include <queue>
- #include <deque>
- #include <unordered_map>
- #include <numeric>
- #include <iomanip>
- using namespace std;
- #define pii pair<int , int>
- #define ll long long
- #define FAST ios_base::sync_with_stdio(false); cin.tie(NULL)
- const long long dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
- const long long dl[2] = {1, -1};
- const long long MOD = 1000000007;
- const long long MAXN = 40005;
- int N, M;
- vector<pii> adj[MAXN]; // node, distance
- int dist[MAXN];
- int depth[MAXN];
- int par[MAXN][22];
- void make_tree(int c, int p, int dep, int di){
- dist[c] = di;
- depth[c] = dep;
- par[c][0] = p;
- for(auto x : adj[c]){
- if(x.first != p){
- make_tree(x.first, c, dep + 1, di + x.second);
- }
- }
- }
- int LCA (int x, int y){
- if(depth[x] < depth[y]){
- swap(x, y);
- }
- if(depth[x] != depth[y]){
- int k = depth[x] - depth[y];
- for(int i = 0; i <= 20; i++){
- if((k & (1 << i)) != 0){
- x = par[x][i];
- }
- }
- }
- if(x == y){
- return x;
- }
- for(int i = 20; i >= 0; i--){
- int xx = par[x][i];
- int yy = par[y][i];
- if(xx != yy){
- x = xx;
- y = yy;
- }
- }
- return par[x][0];
- }
- int main() {
- FAST;
- cin >> N;
- for(int x, y, z, i = 0; i < N - 1; i++){
- cin >> x >> y >> z;
- adj[x].push_back({y, z});
- adj[y].push_back({x, z});
- }
- make_tree(1, 0, 1, 0);
- for(int j = 1; j <= 20; j++){
- for(int i = 2; i <= N; i++){
- par[i][j] = par[par[i][j - 1]][j - 1];
- }
- }
- cin >> M;
- for(int x, y, i = 0; i < M; i++){
- cin >> x >> y;
- int lca = LCA(x, y);
- cout << dist[x] + dist[y] - dist[lca] * 2 << "\n";
- }
- }
- /*
- 7
- 1 6 13
- 6 3 9
- 3 5 7
- 4 1 3
- 2 4 20
- 4 7 2
- 3
- 1 6
- 1 4
- 2 6
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement