Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma comment(linker, "/STACK:67108864")
- #include <vector>
- #include <list>
- #include <iostream>
- #include <algorithm>
- const int MAX_N = 200001;
- int n, logn;
- std::vector<int> parent(MAX_N);
- std::vector<int> depth_level(MAX_N);
- std::vector<std::vector<int>> ancestor(MAX_N);
- std::vector<std::vector<int>> distance(MAX_N);
- void preprocess_dfs(int node, int parent,int depth, int dist_to_parent, std::vector<std::list<std::pair<int, int>>> &adjacency_list)
- {
- depth_level[node] = depth;
- ancestor[node][0] = parent;
- distance[node][0] = dist_to_parent;
- for(int i=1;i<logn;i++)
- ancestor[node][i] = ancestor[ancestor[node][i - 1]][i - 1];
- for(int i=1; i<=logn;i++)
- distance[node][i] = std::max(distance[node][i - 1], distance[ancestor[node][i - 1]][i - 1]);
- for (auto neighbour : adjacency_list[node])
- if (neighbour.first != parent)
- preprocess_dfs(neighbour.first, node, depth + 1, neighbour.second, adjacency_list);
- }
- int lca(int v, int u)
- {
- int max_distance = INT_MIN;
- if (v == u)
- return 0;
- if (depth_level[v] > depth_level[u])
- std::swap(v, u);
- int depth_diff = depth_level[u] - depth_level[v];
- int pow = 1 << logn;
- int i = logn;
- for (; i >= 0;)
- {
- if (pow <= depth_diff)
- {
- max_distance = std::max(max_distance, distance[u][i]);
- u = ancestor[u][i];
- depth_diff = depth_level[u] - depth_level[v];
- }
- pow = pow >> 1;
- i--;
- }
- if(u != v)
- {
- int j = logn;
- while(j>=0)
- {
- if(ancestor[u][j]!=ancestor[v][j])
- {
- max_distance = std::max(max_distance, distance[u][j]);
- max_distance = std::max(max_distance, distance[v][j]);
- u = ancestor[u][j];
- v = ancestor[v][j];
- }
- j--;
- }
- if (u != v)
- {
- max_distance = std::max(max_distance, distance[u][0]);
- max_distance = std::max(max_distance, distance[v][0]);
- }
- }
- return max_distance;
- }
- int main()
- {
- std::ios_base::sync_with_stdio(false);
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- int a, b;
- int cost;
- std::cin >> n;
- int pow = 1;
- logn = 1;
- while (pow <= n) {
- pow *= 2;
- logn++;
- }
- for(int i=0;i<n;i++)
- {
- ancestor[i].resize(logn + 1, 0);
- distance[i].resize(logn + 1, INT_MIN);
- }
- std::vector< std::list< std::pair<int,int>>> adjacency_list(n);
- for (int i = 0; i<n - 1; i++)
- {
- scanf("%d %d %d", &a, &b, &cost);
- adjacency_list[a - 1].push_back(std::make_pair(b - 1,cost));
- adjacency_list[b - 1].push_back(std::make_pair(a - 1,cost));
- }
- preprocess_dfs(0, 0, 0, INT_MIN,adjacency_list);
- int query_num;
- std::cin >> query_num;
- for(int i=0;i<query_num; i++)
- {
- scanf("%d %d", &a, &b);
- std::cout << lca(a - 1, b - 1) << std::endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement