using least common ancestor, mnm and mx array are used for storing minimum and maximum between a node and its ancestors, getting WA after 10th judge
#include <cstdio>
#include <climits>
#include <algorithm>
#include <vector>
#include <cstring>
#include<iostream>
#include<utility>
#include<map>
using namespace std;
const int INF = INT_MAX;
const int MAX = 1<<17;
const int LOG = 17;
map<pair<int,int>,int > mp;
int n;
vector<int> G[MAX];
int root[MAX][LOG], mnm[MAX][LOG],mx[MAX][LOG], pi[MAX], lvl[MAX];bool vis[MAX];
void dfs(int u, int depth) {
int sz = G[u].size(), i, v, w;
lvl[u] = depth;
for(i = 0; i < sz; i++) {
if(vis[G[u][i]]==0){
pi[G[u][i]]=u;
vis[G[u][i]]=1;
dfs(G[u][i],depth+1);
}
}
}
void calcRoot(int n) {
int i, j;
memset(root, -1, sizeof root);
for(i = 1; i <= n; i++){root[i][0] =pi[i];mnm[i][pi[i]]=mx[i][pi[i]]=mp[make_pair(i,pi[i])];}
for(j = 1; 1<<j < n; j++)
for(i = 1; i <= n; i++)
if(root[i][j-1]!=-1){
root[i][j] = root[root[i][j-1]][j-1];
if(root[i][j]!=-1){
//cout<<i<<" "<<root[i][j]<<" "<<root[i][j-1]<<" "<<mnm[i][root[i][j-1]]<<" "<<mp[make_pair(root[i][j],root[i][j-1])]<<endl;
if(mp[make_pair(root[i][j],root[i][j-1])])mnm[i][root[i][j]]=min(mnm[i][root[i][j-1]],mp[make_pair(root[i][j],root[i][j-1])]);
if(mp[make_pair(root[i][j],root[i][j-1])])mx[i][root[i][j]]=max(mx[i][root[i][j-1]],mp[make_pair(root[i][j],root[i][j-1])]);
}
}
}
int lca(int p, int q) {
int i, stp;
if(lvl[p] < lvl[q]) swap(p, q);
for(stp = 1; 1<<stp <= lvl[p]; stp++); stp--;
for(i = stp; i >= 0; i--)
if(lvl[p] - (1<<i) >= lvl[q])
p = root[p][i];
if(p == q) return p;
for(i = stp; i >= 0; i--)
if(root[p][i]!=-1 && root[p][i]!=root[q][i])
p = root[p][i], q = root[q][i];
return pi[p];
}
int main() {
int i,x,y,z,qu,p,q;
scanf("%d", &n);
for(i=0;i<n-1;i++){
scanf("%d%d%d",&x,&y,&z);
mp[make_pair(x,y)]=z;mp[make_pair(y,x)]=z;
G[x].push_back(y);
G[y].push_back(x);
}
vis[1]=1;dfs(1,1);
calcRoot(n);
//cout<<lvl[1]<<" "<<lvl[3]<<endl;
cin>>qu;
for(i=0;i<qu;i++){
cin>>x>>y;
if(pi[x]==y || pi[y]==x){
cout<<mp[make_pair(x,y)]<<" "<<mp[make_pair(x,y)]<<endl;
continue;
}
z=lca(x,y);
//cout<<"arc "<<lvl[x]<<" "<<lvl[y]<<" "<<lvl[z]<<endl;
p=lvl[x]-lvl[z]-1;
q=lvl[y]-lvl[z]-1;
if(z==x){
cout<<mnm[y][lvl[y]-lvl[x]-1]<<" ";
cout<<mx[y][lvl[y]-lvl[x]-1]<<endl;
}else if(z==y){
cout<<mnm[x][lvl[x]-lvl[y]-1]<<" ";
cout<<mx[x][lvl[x]-lvl[y]-1]<<endl;
}else {
cout<<min(mnm[x][root[x][p]],mnm[y][root[y][q]])<<" ";
cout<<max(mx[x][root[x][p]],mx[y][root[y][q]])<<endl;
}
}
return 0;
}