观察性质
当一次移动前后 都成立时, 和 都可以进行移动,并且它们的移动条件是相同的。那么我们只需要找到一个中间状态,使 和 以平均每个数交换次数不超过 次(总交换次数不超过 次)向中间状态转移。
我们让中间状态为 到 的顺序排序。每次进行如下操作:寻找当前最小且不在自己位置上的数(只是为了保证不漏,从哪里都是可行的),然后尝试转移。如果无法转移,那么就尝试转移对应位置上的数,不断操作直到成功转移,然后推及到最初的数,即:
| 数值 | … | |||
|---|---|---|---|---|
| 位置 | … |
用 尝试去交换 ,用 尝试去交换 ,以此类推,直至可以交换。其中表格的位置 与前后顺序无关,只是为了形象表示。
正确性证明
由题意可知,当一个转移无法进行时,满足 。代入表格,即:
由此可以推断出 的结论,矛盾,所以显然不存在“死循环”。
时间复杂度 ,比大多数题解的小根堆做法要优秀
代码实现
#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 ;}
const int N = (1<<20)+7;
int n,a[N],b[N];
vector<pair<int,int> > opa,opb;
void calc(int p[],vector<pair<int,int> >& op)
{
for(int i=0;i<n;i++)
while(p[i] != i)
{
int u = i,v = p[i];
while((p[u]^p[v]) > (u^v)) u = v,v = p[u];
op.push_back(make_pair(u,v)),swap(p[u],p[v]);
}
return ;
}
void Main()
{
int k = read();
n = 1 << k;
for(int i=0;i<n;i++) a[i] = read();
for(int i=0;i<n;i++) b[i] = read();
calc(a,opa);
calc(b,opb);
int m = (int)opa.size()+(int)opb.size();
out(m);
for(int i=0;i<(int)opa.size();i++)
write(opa[i].first),putchar(' '),out(opa[i].second);
for(int i=(int)opb.size()-1;i>=0;i--)
write(opb[i].first),putchar(' '),out(opb[i].second);
return ;
}
}