并查集+按秩合并
#include <bits/stdc++.h> using namespace std; const int N = 5e5+50; int n,lst; struct UnionTable { int f[N],s[N],v[N],d[N]; void init(int n) { for(int i=1; i<=n; i++) f[i]=i,v[i]=0,s[i]=1; } int find(int x) { if(f[x]^x) { int fa=find(f[x]); d[x]=d[f[x]]+1; return fa; } else return x; } void Union(int x,int y,int c) { int f1=find(x),f2=find(y); if(f1==f2) return; if(s[f1]>s[f2]) f[f2]=f1,v[f2]=c,s[f1]+=s[f2]; else f[f1]=f2,v[f1]=c,s[f2]+=s[f1]; } int Query(int x,int y) { int f1=find(x),f2=find(y),r=0; if(f1!=f2) return -1; while (x!=y) { if(d[x]<d[y]) swap(x,y); r=max(r,v[x]),x=f[x]; } return r; } } un; int main() { int T,m; scanf ("%d",&T); while (T--) { scanf ("%d%d",&n,&m); un.init(n); int c=0; while (m--) { int op,u,v; scanf ("%d%d%d",&op,&u,&v); if(op==1) un.Union(u,v,++c); else {printf("%d\n",un.Query(u,v));++c;} } } return 0; }