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 = 100005;
- int N, K;
- vector<pii> adj[MAXN];
- int depth[MAXN];
- int par[MAXN][22];
- int mine[MAXN][22];
- int maxe[MAXN][22];
- void make_tree(int c, int p, int dep, int dis){
- depth[c] = dep;
- if(c != 1){
- mine[c][0] = dis;
- maxe[c][0] = dis;
- par[c][0] = p;
- }
- for(auto x : adj[c]){
- if(x.first != p){
- make_tree(x.first, c, dep + 1, 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;
- memset(mine, 2e9, sizeof(mine));
- 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];
- mine[i][j] = min(mine[i][j - 1], mine[par[i][j - 1]][j - 1]);
- maxe[i][j] = max(maxe[i][j - 1], maxe[par[i][j - 1]][j - 1]);
- }
- }
- cin >> K;
- for(int x, y, i = 0; i < K; i++){
- cin >> x >> y;
- int lca = LCA(x, y);
- int mind = 2e9, maxd = 0;
- if(depth[y] != depth[lca]){
- int k = depth[y] - depth[lca];
- for(int j = 0; j <= 20; j++){
- if((k & (1 << j)) != 0){
- mind = min(mind, mine[y][j]);
- maxd = max(maxd, maxe[y][j]);
- y = par[y][j];
- }
- }
- }
- if(depth[x] != depth[lca]){
- int k = depth[x] - depth[lca];
- for(int j = 0; j <= 20; j++){
- if((k & (1 << j)) != 0){
- mind = min(mind, mine[x][j]);
- maxd = max(maxd, maxe[x][j]);
- x = par[x][j];
- }
- }
- }
- cout << mind << " " << maxd << "\n";
- }
- }
- /*
- 9
- 1 2 2
- 2 3 1
- 3 4 5
- 2 7 4
- 1 5 3
- 5 6 1
- 5 9 2
- 1 8 3
- 5
- 6 9
- 7 8
- 9 4
- 1 2
- 7 3
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement