题解:P10258 [COCI 2023/2024 #5] Bitovi

· · 题解

我们很容易想到:对于一个 b_i,如果当前已经有 a_j = b_i 了,就不用管。否则,我们随便取一个没有用处的 a_i,得想办法让其变成 b_i。

对于我们要将 x 变成 y,容易想到令 c = \operatorname{lowbit} (x \operatorname{xor} y),然后令 x ^= c 就离变成 y 更近了一步。但是,如果当前 x \operatorname{xor} c 这个值已经有了,那么我们就不能直接改变数字。不妨先不操作这一步,然后用原来的 x \operatorname{xor} c 去操作,操作完成之后我们再令 x ^= c,容易发现这时候原来的 x \operatorname{xor} c 已经变成了 b_i,所以我们可以放心的异或。

注意这时候是不改变之前 x \operatorname{xor} c 的形态的,即:如果它之前是有贡献的,现在还是有贡献的,相反也一样,反正最后还是要给其他的 b_i 做贡献。

Code:

#include<bits/stdc++.h>
#define pre(i, l, r)    for(int i = (l); i <= (r); ++i)
#define fpre(i, r, l)   for(int i = (r); i >= (l); --i)
#define ll long long

using namespace std;

const int maxn = 3e5 + 5;
const int inf = 1e9;
const ll lnf = 2e18;

int n;
int a[maxn], b[maxn];
int vis[maxn], vos[maxn];
vector<pair<int,int>> ans;

void change(int x, int y)
{
    if(x == y)  return; // 相等就直接return
    int c = (x ^ y) & -(x ^ y); // 取最小的不同的数字
  //由于x=y的情况已经特判了,所以不用管c=0的情况。
    if(!vis[x ^ c]) // 如果一开始没有,就将x 变成 x ^ c
        ans.emplace_back(x, x ^ c);
    change(x ^ c, y); // 递归
    if(vis[x ^ c])
        ans.emplace_back(x, x ^ c); // 反之,现在vis[x^c] 已经是空的了,可以放心的异或了。
}

int main()
{
    scanf("%d", &n);
    pre(i, 1, n)
        scanf("%d", &a[i]), vis[a[i]]++;
    pre(i, 1, n)
        scanf("%d", &b[i]), vos[b[i]]++;
    vector<int> res; // 记录没用的a[i]
    pre(i, 1, n)
        if(!vos[a[i]])
            res.emplace_back(a[i]);
    pre(i, 1, n)
    {
        if(vis[b[i]])   continue; // 如果已经有值了就不管了
        int x = res.back();
        res.pop_back(); // 取一个没有被用过的值
        change(x, b[i]); // 将x 变成 b[i]
        vis[x] = 0; // 更新vis数组
        vis[b[i]] = 1;
    }
    printf("%d\n", ans.size());
    for(auto y : ans)
        printf("%d %d\n", y.first, y.second);
    //输出答案
    return 0;
}