local UF = {} UF.create = function(self, n) self.parent = {} self.g = {} for i = 1, n do self.parent[i] = i self.g[i] = true end end UF.getroot = function(self, idx) local parent = self.parent local idx_update = idx while parent[idx] ~= idx do idx = parent[idx] end while parent[idx_update] ~= idx do parent[idx_update], idx_update = idx, parent[idx_update] end return idx end UF.unite = function(self, a, b) local ra = self:getroot(a) local rb = self:getroot(b) self.g[rb] = nil self.parent[b], self.parent[rb] = ra, ra end UF.new = function(n) local obj = {} setmetatable(obj, {__index = UF}) obj:create(n) return obj end local n = io.read("*n") local uf = UF.new(n) local q = io.read("*n") for iq = 1, q do local tp = io.read("*n") if tp == 1 then local a, b = io.read("*n", "*n") uf:unite(a, b) else local a = io.read("*n") local g = uf.g local k1, v1 = next(g) local k2, v2 = next(g, k1) if k2 then local r = uf:getroot(a) print(k1 + k2 - r) else print(-1) end end end