观察性质
当一次移动前后 都成立时, 和 都可以进行移动,并且它们的移动条件是相同的。那么我们只需要找到一个中间状态,使 和 以平均每个数交换次数不超过 次(总交换次数不超过 次)向中间状态转移。
我们让中间状态为 到 的顺序排序。每次进行如下操作:寻找当前最小且不在自己位置上的数(只是为了保证不漏,从哪里都是可行的),然后尝试转移。如果无法转移,那么就尝试转移对应位置上的数,不断操作直到成功转移,然后推及到最初的数,即:
| 数值 | … | |||
|---|---|---|---|---|
| 位置 | … |
用 尝试去交换 ,用 尝试去交换 ,以此类推,直至可以交换。其中表格的位置 与前后顺序无关,只是为了形象表示。
正确性证明
由题意可知,当一个转移无法进行时,满足 。代入表格,即:
由此可以推断出 的结论,矛盾,所以显然不存在“死循环”。
代码实现
#include <bits/stdc++.h>
using namespace std;
namespace WFH{void Main();}
signed main(){return WFH::Main(),0;}
namespace WFH
{
inline int read()
{
long long x = 0, f = 1;
char ch = getchar();
while(ch > '9' || ch < '0'){if(ch == '-') f = -f; ch = getchar();}
while(ch >= '0' && ch <= '9') x = x*10 + ch - '0', ch = getchar();
return x * f;
}
inline void write(int x)
{
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return ;
}
inline void out(int x){write(x); putchar('\n'); return ;}
#define pr pair<int,int>
#define fi first
#define se second
const int N = (1<<20)+7;
int n,m,a[N],b[N],rev[N];
vector<pr> calc(int p[])
{
vector<pr> op;
priority_queue<pr,vector<pr>,greater<pr>> q;
for(int i=0;i<m;i++) if(p[i]!=i) q.push({i^p[i],i});
while(!q.empty())
{
pr t = q.top();
q.pop();
int x = t.se, w = t.fi;
if(p[x]==x || (p[x]^x)!=w) continue;
int y = rev[x];
op.push_back({x,y});
swap(p[x],p[y]);
rev[p[x]] = x, rev[p[y]] = y;
if(p[y]!=y) q.push({y^p[y],y});
}
return op;
}
void Main()
{
n = read();
m = 1<<n;
for(int i=0;i<m;i++) a[i] = read();
for(int i=0;i<m;i++) b[i] = read();
for(int i=0;i<m;i++) rev[a[i]] = i;
vector<pr> pa = calc(a);
for(int i=0;i<m;i++) rev[b[i]] = i;
vector<pr> pb = calc(b);
int len = pa.size() + pb.size();
out(len);
for(int i=0;i<(int)pa.size();i++) write(pa[i].fi), putchar(' '), out(pa[i].se);
for(int i=(int)pb.size()-1;i>=0;i--) write(pb[i].fi), putchar(' '), out(pb[i].se);
return ;
}
}