1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include<bits/stdc++.h> using namespace std;
#define pii pair<int, int> #define mp make_pair #define pb push_back #define fr first #define sc second
inline int rd() { int x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
#define N 100007 int a[N], rt[N], totnode;
struct node {int ls, rs, val;} c[N << 5];
inline int newnode() {return ++totnode;}
inline void pushup(int nw) { c[nw].val = c[c[nw].ls].val + c[c[nw].rs].val; }
void update(int &nw, int l, int r, int p, int val) { int t = newnode(); c[t] = c[nw]; nw = t; if (l == r) {c[nw].val += val; return;} int mid = (l + r) >> 1; if (p <= mid) update(c[nw].ls, l, mid, p, val); else update(c[nw].rs, mid + 1, r, p, val); pushup(nw); }
int query(int nwu, int nwv, int nwlca, int l, int r, int k) { if (l == r) return l; int mid = (l + r) >> 1; int cnt = c[c[nwu].ls].val + c[c[nwv].ls].val - 2 * c[c[nwlca].ls].val; if (cnt >= k) return query(c[nwu].ls, c[nwv].ls, c[nwlca].ls, l, mid, k); else return query(c[nwu].rs, c[nwv].rs, c[nwlca].rs, mid + 1, r, k - cnt); }
#define M 50007
vector<pii> e[M]; int dep[M], fa[M][18], t, mx;
inline void dfs(int u, int w) { rt[u] = rt[fa[u][0]]; if (w != 0) update(rt[u], 1, mx, w, 1); for (int i = 1; i <= t; ++i) fa[u][i] = fa[fa[u][i - 1]][i - 1]; for (auto cur : e[u]) { int v = cur.fr; if (v != fa[u][0]) { fa[v][0] = u; dep[v] = dep[u] + 1; dfs(v, cur.sc); } } }
inline int lca(int u, int v) { if (dep[u] > dep[v]) swap(u, v); for (int i = t; i >= 0; --i) if (dep[fa[v][i]] >= dep[u]) v = fa[v][i]; if (u == v) return u; for (int i = t; i >= 0; --i) if (fa[u][i] != fa[v][i]) { u = fa[u][i]; v = fa[v][i]; } return fa[u][0]; }
inline void work() { totnode = 0; int n = rd(); t = __lg(n - 1) + 1; mx = 0; for (int i = 1; i <= n; ++i) { e[i].clear(); dep[i] = 0; for (int j = 1; j <= t; ++j) fa[i][j] = 0; } for (int i = 1; i < n; ++i) { int u = rd(), v = rd(), w = rd(); mx = max(mx, w); e[u].pb(mp(v, w)); e[v].pb(mp(u, w)); } fa[1][0] = 1; dfs(1, 0); for (int q = rd(); q; --q) { int u = rd(), v = rd(); int tlca = lca(u, v), len = dep[u] + dep[v] - 2 * dep[tlca]; if (len % 2) { printf("%.1lf\n", 1.0 * query(rt[u], rt[v], rt[tlca], 1, mx, len / 2 + 1)); } else { printf("%.1lf\n", 1.0 * (query(rt[u], rt[v], rt[tlca], 1, mx, len / 2) + query(rt[u], rt[v], rt[tlca], 1, mx, len / 2 + 1)) / 2); } } }
int main() { for (int t = rd(); t; --t) work(); return 0; }
|