分类讨论下就行
不知道正解咋样
好像只有我没A T2
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL long lon
const int MAXN=1e5+10;
const int LOGN=17+1;
int depth[MAXN],to[MAXN][LOGN],mmax[MAXN][LOGN];
int team[MAXN],head,tail;
int tot,g[MAXN],num[MAXN*2],nnext[MAXN*2],cost[MAXN*2];
void add(int x,int y,int z)
{
tot++;
nnext[tot]=g[x];
g[x]=tot;
num[tot]=y;
cost[tot]=z;
}
int ask(int x,int y)
{
int ans=mmax[0][0];
if(depth[x]<depth[y]) swap(x,y);
for(int i=17;i>=0;i--)
if(depth[to[x][i]]>=depth[y])
{
ans=max(ans,mmax[x][i]);
x=to[x][i];
}
for(int i=17;i>=0;i--)
if(to[x][i]!=to[y][i])
{
ans=max(ans,max(mmax[x][i],mmax[y][i]));
x=to[x][i];
y=to[y][i];
}
if(x!=y)
{
ans=max(ans,max(mmax[x][0],mmax[y][0]));
x=to[x][0];
y=to[y][0];
}
return ans;
}
int q_lca(int x,int y)
{
if(depth[x]<depth[y]) swap(x,y);
for(int i=17;i>=0;i--)
if(depth[to[x][i]]>=depth[y])
x=to[x][i];
if(x==y) return x;
for(int i=17;i>=0;i--)
if(to[x][i]!=to[y][i])
{
x=to[x][i];
y=to[y][i];
}
return to[x][0];
}
int main()
{
freopen("tree.in","r",stdin);
freopen("tree.out","w",stdout);
int n,m;
scanf("%d",&n);
for(int i=1;i<n;i++)
{
int x,y,z;
scanf("%d %d %d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
team[++tail]=1;depth[1]=1;
while(head<tail)
{
int x=team[++head];
for(int i=1;i<=17;i++)
{
mmax[x][i]=max(mmax[x][i-1],mmax[to[x][i-1]][i-1]);
to[x][i]=to[to[x][i-1]][i-1];
}
for(int i=g[x];i;i=nnext[i])
{
int tmp=num[i];
if(tmp==to[x][0]) continue;
depth[tmp]=depth[x]+1;
to[tmp][0]=x;
mmax[tmp][0]=cost[i];
team[++tail]=tmp;
}
}
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
int x,y,q;
scanf("%d %d %d",&x,&y,&q);
int lca=q_lca(x,y);
int lcax=q_lca(x,q);
int lcay=q_lca(y,q);
int qlca=q_lca(lca,q);
if((lca==qlca&&(lcax==q||lcay==q))) printf("%d\n",0);
else
{
int ans=ask(q,lca);
if(qlca!=lcax) ans=min(ans,ask(q,lcax));
if(qlca!=lcay) ans=min(ans,ask(q,lcay));
printf("%d\n",ans);
}
}
fclose(stdin);
fclose(stdout);
return 0;
}