大概抄了 第一篇题解 的思路(((
#include <bits/stdc++.h>
using namespace std;
int n, m;
stack<int> s[405];
bool b[405];
queue<pair<int, int>> q;
int count(stack<int> X, int y) {
int cnt = 0;
while(!X.empty()) {
if(X.top() == y) cnt++;
X.pop();
}
return cnt;
}
void work(int a, int b, int c, int y) {
auto X = s[a], H = s[b], N = s[c];
int A = count(X, y);
for(int i = 0; i < A; i++) {
q.push({b, c});
N.push(H.top());
H.pop();
}
while(!X.empty()) {
if(X.top() == y) {
q.push({a, b});
H.push(X.top());
} else {
q.push({a, c});
N.push(X.top());
}
X.pop();
}
for(int i = 0; i < m - A; i++) {
q.push({c, a});
X.push(N.top());
N.pop();
}
for(int i = 0; i < A; i++) {
q.push({b, a});
X.push(H.top());
H.pop();
}
while(!N.empty()) {
q.push({c, b});
H.push(N.top());
N.pop();
}
s[a] = X, s[b] = H, s[c] = N;
}
int full(int y) {
for(int i = 1; i <= n + 1; i++)
if(y != i && !b[i] && s[i].size() == m)
return i;
}
int empty() {
for(int i = 1; i <= n + 1; i++)
if(!b[i] && s[i].empty())
return i;
}
int have() {
for(int i = 1; i <= n + 1; i++)
if(!b[i] && !s[i].empty())
return i;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// freopen("ball1.in", "r", stdin);
// freopen("ball1.out", "w", stdout);
cin>>n>>m;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++) {
int x;
cin>>x;
s[i].push(x);
}
for(int y = 1; y < n; y++) {
int e = empty();
for(int i = 1; i <= n; i++)
if(!b[i] && !s[i].empty() && i != e) {
int f = full(i);
// cout<<"work(i"<<i<<",f"<<f<<",e"<<e<<",y"<<y<<")"<<endl;
work(i, f, e, y);
while(s[i].top() == y) {
q.push({i, e});
s[e].push(s[i].top());
s[i].pop();
}
}
int h = have(), i = 1;
while(!s[h].empty() && i <= n + 1) {
if(h == i) i++;
while(s[i].size() < m && !s[h].empty()) {
q.push({h, i});
s[i].push(s[h].top());
s[h].pop();
}
i++;
}
b[e] = 1;
}
cout<<q.size()<<endl;
while(!q.empty()) {
cout<<q.front().first<<" "<<q.front().second<<endl;
q.pop();
}
return 0;
}