提交时间:2022-07-13 12:30:24
运行 ID: 51669
#include<iostream> #include<algorithm> #include<set> #define fst(a,b,c) for(int a=(b);a<=(c);a++) #define est(x) for(int i=hd[x],y=to[i];i;i=nt[i],y=to[i]) using namespace std; const int N=1e5+100,MX=1e5,Len=150; int n,m,ans[N]; int p[N],cnt[N],fa[N],dep[N],siz[N],hea[N],top[N],dfn[N][2],ord[N*2],blo[N*2],num; set<int> sig; int hd[N],to[N*2],vl[N*2],nt[N*2],tot; struct Query{ int lca,l,r,mx,id; }q[N]; int read(){ char in=getchar(); int x=0; while(!isdigit(in)) in=getchar(); while(isdigit(in)) x=x*10+(in^48),in=getchar(); return x; } void add(int x,int y,int z){ to[++tot]=y;vl[tot]=z;nt[tot]=hd[x];hd[x]=tot; to[++tot]=x;vl[tot]=z;nt[tot]=hd[y];hd[y]=tot; } void build1(int x){ siz[x]=1; est(x){ if(y==fa[x]) continue; fa[y]=x; dep[y]=dep[x]+1; p[y]=vl[i]; build1(y); siz[x]+=siz[y]; if(siz[y]>siz[hea[x]]) hea[x]=y; } } void build2(int x,int Fa){ ord[dfn[x][0]=++num]=x; top[x]=Fa; if(hea[x]){ build2(hea[x],Fa); est(x){ if(y==fa[x]||y==hea[x]) continue; build2(y,y); } } ord[dfn[x][1]=++num]=x; return; } int LCA(int x,int y){ while(top[x]!=top[y]){ if(dep[top[x]]>dep[top[y]]) x=fa[top[x]]; else y=fa[top[y]]; } return (dep[x]<dep[y])?x:y; } bool cmp(Query x,Query y){ if(blo[x.l]!=blo[y.l]) return x.l<y.l; else if(blo[x.r]!=blo[y.r]) return x.r<y.r; else return (blo[x.r]&1)?x.r<y.r:x.r>y.r; } bool ext(int x){return sig.count(x);} void ins(int x){ // printf("+ %d\n",x); sig.insert(x); } void del(int x){ // printf("- %d\n",x); sig.erase(x); } int main(){ freopen("game.in","r",stdin); freopen("game.out","w",stdout); int x,y,z,mx,l,r; n=read(); fst(i,1,n) blo[i]=(i+Len-1)/Len; fst(i,1,n-1){ x=read(),y=read(),z=read(); add(x,y,z); } p[1]=MX+1; build1(1); build2(1,1); // fst(i,1,2*n) printf("%d ",ord[i]); puts(""); m=read(); fst(i,1,m){ x=read(),y=read(),mx=read(); if(dfn[x][0]>dfn[y][0]) swap(x,y); if(dfn[y][1]<dfn[x][1]) q[i].l=dfn[x][0]; else q[i].l=dfn[x][1]; q[i].r=dfn[y][0]; q[i].lca=LCA(x,y); q[i].mx=mx; q[i].id=i; // printf("lca = %d\n",q[i].lca); } sort(q+1,q+m+1,cmp); l=1,r=0; fst(i,1,m){ while(r<q[i].r){ r++; if(ext(p[ord[r]])) del(p[ord[r]]); else ins(p[ord[r]]); } while(l>q[i].l){ l--; if(ext(p[ord[l]])) del(p[ord[l]]); else ins(p[ord[l]]); } while(r>q[i].r){ if(ext(p[ord[r]])) del(p[ord[r]]); else ins(p[ord[r]]); r--; } while(l<q[i].l){ if(ext(p[ord[l]])) del(p[ord[l]]); else ins(p[ord[l]]); l++; } if(l<=dfn[q[i].lca][0]&&dfn[q[i].lca][0]<=r&&dfn[q[i].lca][1]>r){ if(ext(p[q[i].lca])) del(p[q[i].lca]); else ins(p[q[i].lca]); } auto it=sig.upper_bound(q[i].mx); // printf("mx = %d l = %d r = %d *it = %d %d\n",q[i].mx,l,r,*it,it==sig.end()); // printf("%d\n",*it); if(sig.size()) printf("%d\n",*sig.begin()); it=sig.upper_bound(q[i].mx); if(it==sig.begin()||sig.size()==0) ans[q[i].id]=q[i].mx; else ans[q[i].id]=q[i].mx-*(--it); if(l<=dfn[q[i].lca][0]&&dfn[q[i].lca][0]<=r&&dfn[q[i].lca][1]>r){ if(ext(p[q[i].lca])) del(p[q[i].lca]); else ins(p[q[i].lca]); } } fst(i,1,m) printf("%d\n",ans[i]); return 0; }