/// [A][M][C][B][N] ///
#include <bits/stdc++.h>
using namespace std;
const int mod = 9973;
const int inf = 0x3f3f3f3f;
const char sp = ' ', nl = '\n';
ifstream fin("mergeheap.in");
ofstream fout("mergeheap.out");
set<int> s[101];
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n, q;
fin >> n >> q;
while (q--) {
int t, a, b;
fin >> t >> a;
if (t != 2)
fin >> b;
if (t == 1) {
s[a].insert(b);
}
else if (t == 2) {
int mx = *(--s[a].end());
fout << mx << nl;
s[a].erase(mx);
}
else {
if (s[a].size() < s[b].size())
swap(s[a], s[b]);
for (auto& x : s[b])
s[a].insert(x);
s[b] = set<int>();
}
}
}