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 107
| #include <bits/stdc++.h>
using namespace std; const int N = 1e5 + 10; const int M = 1e6 + 10; const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-3; struct node{ int u,v,w,next; }a[M]; int f[N],cnt; void add(int u,int v,int w){ a[++cnt].v = v; a[cnt].w = w; a[cnt].next = f[u]; f[u] = cnt; } int lg; int father[N][30],root[N],Time[N][30],dep[N]; int lca(int u,int v){ int x = u,y = v; if(dep[u] < dep[v]) swap(u,v); int Max = 0; for(int i = lg;i>=0;i--){ if(dep[father[u][i]] >= dep[v]) { Max = max(Max,Time[u][i]); u = father[u][i]; } } if(u==v) return Max; for(int i = lg;i>=0;i--){ if(father[u][i]!=father[v][i]){ Max = max(Max,max(Time[u][i],Time[v][i])); u = father[u][i],v = father[v][i]; } } return max(Max,max(Time[u][0],Time[v][0])); } void dfs(int u,int fa){ for (int j = 1; j <= lg; j++) { father[u][j] = father[father[u][j - 1]][j - 1]; Time[u][j] = max(Time[u][j - 1], Time[father[u][j - 1]][j - 1]); } for(int i = f[u];i;i = a[i].next){ int v = a[i].v,w = a[i].w; if(v==fa) continue; dep[v] = dep[u] + 1; father[v][0] = u; Time[v][0] = w; dfs(v,u); } } int c[N]; int getf(int v){ if(c[v]==v) return v; else return c[v] = getf(c[v]); } void solve(){ cnt = 0; memset(f,0,sizeof f); int n,m; cin>>n>>m; for(int i = 1;i<=n;i++) c[i] = i; lg = (int)(log(n)/log(2))+1; int type,u,v; vector<pair<int,pair<int,int>>> query; for(int i = 1;i<=m;i++){ scanf("%d%d%d",&type,&u,&v); if(type==1){ int id1 = getf(u),id2 = getf(v); if(id1==id2) continue; c[id1] = id2; add(id1, id2, i); add(id2,id1,i); }else{ query.push_back({i,{u,v}}); } } for(int i =1;i<=n;i++) if(c[i]==i){ father[i][0] = i; Time[i][0] = 0; dep[i] = 0; dfs(i,-1); } for(auto it:query){ int t = it.first,u = it.second.first,v = it.second.second; if(u==v) puts("0"); else{ int t1 = getf(u),t2 = getf(v); if(t1!=t2) puts("-1"); else{ int res = lca(u,v); printf("%d\n",res>t?-1:res); } } } } int main(){ int t; cin >> t; while(t--){ solve(); } return 0; }
|