RT,第二篇题解的思路
#include <bits/stdc++.h>
using namespace std;
#define M 410
int n,m,ans;
struct node
{
int bal[M],siz,cnt[M];
}st[M];
struct Aas
{
int X,Y;
}Ans[M*M*M];
void move(int x,int y)
{
ans++;int V=st[x].bal[st[x].siz];
Ans[ans].X=x;
Ans[ans].Y=y;
st[y].siz++;st[x].siz--;
if(st[y].siz>m||st[x].siz<0) cout<<"Error"<<endl;
st[y].bal[st[y].siz]=V;
st[y].cnt[V]++;
st[x].cnt[V]--;
}
void moved(int x,int y,int z) {for(int i=1;i<=z;i++) move(x,y);}
void Col(int A,int B,int C,int k)
{
int i=st[A].siz;
for(;i>=1;i--)
{
if(st[A].bal[i]==k)
{
if(st[B].siz>=m) move(A,C);
if(st[B].siz<m) move(A,B);
}
if(st[A].bal[i]!=k)
{
if(st[C].siz>=m) move(A,B);
if(st[C].siz<m) move(A,C);
}
}
}
void Do0(int x)
{
int Cnt=st[2].siz-st[2].cnt[x];
moved(x,x+1,st[2].cnt[x]);
Col(2,x,x+1,x);moved(x+1,2,Cnt);
Col(1,x+1,2,x);
swap(st[1],st[x+1]);swap(st[2],st[x]);
}
void Sol2(int x)
{
if(x==1) return;
int ff=st[1].cnt[1];
moved(2,3,ff);Col(1,2,3,1);moved(2,1,ff);
moved(3,1,m-ff);moved(3,2,st[3].siz);moved(1,3,m-ff);
Col(2,1,3,1);
}
void Up(int x,int k)
{
moved(x,x+1,st[x-1].cnt[k]);
Col(x-1,x,x+1,k);
node fa,fb,fc;
fa=st[x-1];fb=st[x];fc=st[x+1];
st[x-1]=fc;st[x]=fa;st[x+1]=fb;
}
void Sol(int x)
{
if(x<=2) {Sol2(2);return ;}
Do0(x);int ff;
for(int i=x;i>=2;i--) Up(i,x);
for(int i=x+1;i>=3;i--)
{
ff=st[i].cnt[x];
moved(i,2,ff);
moved(1,i,ff);
}
swap(st[2],st[x+1]);swap(st[1],st[x]);
Sol(x-1);
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>st[i].bal[j];
st[i].cnt[st[i].bal[j]]++;
}
st[i].siz=m;
}
Sol(n);
cout<<ans<<endl;
for(int i=1;i<=ans;i++) cout<<Ans[i].X<<' '<<Ans[i].Y<<endl;
return 0;
}