提交时间:2022-07-13 12:29:20

运行 ID: 51665

#include <cstdio> #include <algorithm> using namespace std; const int N = 1e5 + 5; int n,m,a,b,c,t,cnt,maxn,tot,head[N],nex[2*N],e[2*N][2],dep[N],q[N],w[N],s[N],f[N]; void add_(int x,int y,int z) { tot++; e[tot][0] = y,e[tot][1] = z; nex[tot] = head[x],head[x] = tot; } void dfs(int x) { int y; for(int i = head[x]; i; i = nex[i]) { y = e[i][0]; if(y == f[x]) continue; dep[y] = dep[x] + 1; q[y] = e[i][1]; f[y] = x; dfs(y); } } void lca(int x,int y) { if(dep[x] < dep[y]) swap(x,y); while(dep[x] > dep[y]) { w[++cnt] = q[x]; x = f[x]; } while(x != y) { w[++cnt] = q[x]; w[++cnt] = q[y]; x = f[x],y = f[y]; } } int main() { scanf("%d",&n); for(int i = 1; i < n; i++) { scanf("%d%d%d",&a,&b,&c); add_(a,b,c); add_(b,a,c); } dfs(1); scanf("%d",&m); while(m--) { scanf("%d%d%d",&a,&b,&c); if(c < 1) { printf("0\n"); continue; } cnt = 0; lca(a,b); maxn = -1; for(int i = 1; i <= cnt; i++) if(w[i] <= c && maxn < w[i]) { t = i; maxn = w[i]; } if(maxn == -1) printf("%d\n",c); else printf("%d\n",c - w[t]); } return 0; }