#include<bits/stdc++.h>
using namespace std;
#define fr(ii,ss,tt) for(int ii=ss;ii<=tt;ii++)
#define rf(ii,ss,tt) for(int ii=ss;ii>=tt;ii--)
#define pii pair<int,int>
#define pt printf
#define x first
#define y second
#define siz(x) ((int)size(x))
#define pb push_back
#define eb emplace_back
#define all(a) begin(a),end(a)
#define input(f) freopen(f,"r",stdin)
#define output(f) freopen(f,"w",stdout)
template<typename T>bool tomax(T&x,const T&y) {
if(x<y)return x=y,true;
return false;
}
template<typename T>bool tomin(T&x,const T&y) {
if(x>y)return x=y,true;
return false;
}
#define gc() getchar()
#define pc(c) putchar(c)
inline void rd(auto&x,auto&...y) {
char ch;
bool f=0;
while(!isdigit(ch=gc()))if(ch=='-')f=1;
x=0;
do {
x=(x<<1)+(x<<3)+(ch^48);
} while(isdigit(ch=gc()));
if(f)x=-x;
if constexpr(sizeof...(y))rd(y...);
}
#ifndef ONLINE_JUDGE
#define DF(T) void prt(T x){cout<<x;}
DF(int)DF(char)DF(string)DF(bool)DF(long long)DF(unsigned int)
void prt(auto x);
void prt(pair<auto,auto> x) {
pc('{');
prt(x.first);
pc(',');
prt(x.second);
pc('}');
}
void pp(auto x,auto y) {
pc('{');
for(; x!=y; ++x) {
prt(*x);
pc(',');
}
printf("\b}");
}
void pp(auto x,int y) {
prt(x,x+y);
}
void prt(auto x) {
pp(begin(x),end(x));
}
void pl(auto x,auto...y) {
prt(x);
if constexpr(sizeof...(y))pl(y...);
else pc('\n');
}
void ppl(auto x,auto xx,auto...y) {
pp(x,xx);
if constexpr(sizeof...(y))ppl(y...);
else pc('\n');
}
#define Z(x...) cout<<#x<<":",pl(x)
#define ZZ(x...) cout<<#x<<":",ppl(x)
#else
#define Z(...)
#define ZZ(...)
#endif
#define int long long
const int N=2e6+6,S=19;
mt19937 gen(chrono::steady_clock::now().time_since_epoch().count());
int n,q;
list<int>a[N];
struct Node{
int c[2];
int sz;
}t[N*(S+2)];int rt[N],tot;
#define c(i,j) t[i].c[j]
#define sz(i) t[i].sz
int merge(int x,int y){
if(!x||!y){
return x+y;
}
sz(x)+=sz(y);
c(x,0)=merge(c(x,0),c(y,0));
c(x,1)=merge(c(x,1),c(y,1));
return x;
}
void add(int i,int p,int v){
int*c=&rt[i];
rf(b,S,-1){
int&cur=*c;
if(!cur)cur=++tot;
sz(cur)+=v;
if(b==-1)return;
c=&c(cur,p>>b&1);
}
}
int ask(vector<int>T){
long long nn=0;
for(int&i:T){
nn+=a[i].size();
i=rt[i];
}
int ret=0;
fr(_,0,S){
long long ls=0,rs=0;
for(int i:T){
ls+=sz(c(i,0));
rs+=sz(c(i,1));
}
if(ls>nn/2){
ret=(ret<<1);
for(int&i:T)i=c(i,0);
}else if(rs>nn/2){
ret=(ret<<1|1);
for(int&i:T)i=c(i,1);
}else{
return -1;
}
}
return ret;
}
void ins(int i,int v) {
a[i].eb(v);
add(i,v,1);
}
void del(int i) {
add(i,a[i].back(),-1);
a[i].pop_back();
}
signed main() {
rd(n,q);
fr(i,1,n) {
int l;
rd(l);
while(l--) {
int v;
rd(v);
ins(i,v);
}
}
while(q--) {
int o,x,y,z,m;
vector<int>t;
rd(o);
if(o==1) {
rd(x,y);
ins(x,y);
}
if(o==2) {
rd(x);
del(x);
}
if(o==3) {
int l;
rd(l);
t.resize(l);
fr(i,0,l-1){
rd(t[i]);
}
pt("%d\n",ask(t));
}
if(o==4) {
rd(x,y,z);
rt[z]=merge(rt[x],rt[y]);
m=0;
if(a[x].size()>a[y].size())swap(x,y),m=1;
a[z].swap(a[y]);
for(auto e:a[x]) {
m==0?a[z].push_front(e):a[z].push_back(e);
}
move(a[x]);
}
}
return 0;
}