题解:P16325 【MX-J29-T4】XOR and Swap
观察性质
当一次移动前后
我们让中间状态为
| 数值 | ... | |||
|---|---|---|---|---|
| 位置 | ... |
用
正确性证明
由题意可知,当一个转移无法进行时,满足
由此可以推断出
时间复杂度
代码实现
#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 ;
}
}