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

· · 题解

题意:

给定两个大小为 n 数集 A 和 B。每次操作,可以从集合 A 选择一个任意元素,并改变其二进制中一个数位(改变后不能是改变前 A 中任何一个元素)。 经过一系列操作,输出使得集合 A 与集合 B 完全相同的方案数,并构造方案。

题解:

首先,对于 A 和 B 中都存在的数是没有必要考虑的。然后枚举 B 中的元素 x,如果 x \not \in A,那么需要把 A 中的一个元素变为 x。我们考虑找出 A 中不属于 B 的最小元素 y,把它变为 x。

思考如何构造方案。容易想到拆位。对于 y 的第 i 位 a 和 x 的第 i 位 b。如果 a\not =b,那么就需要把这一位修改掉。注意到将 a 修改后可能会与 A 集合内的元素重复,所以在修改 a 之前,需要把重复元素修改一下。直接递归修改即可。

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
// # define int long long 
# define lc u << 1
# define rc u << 1 | 1
# define fi first
# define se second
# define endl "\n"
const int N = (1 << 20) + 5;

int n;
int a[N], b[N];
int pos[N];
map <int, bool> mp;
struct node
{
    int x, y;
} ans[N]; int tot;
set <int> kexuan;
void addans (int x, int na)
{
    ans[ ++ tot] = {a[x], na};
    pos[a[x]] = 0;
    if (mp[a[x]])
        kexuan.insert (x);
    a[x] = na;
    pos[a[x]] = x;
    if (mp[a[x]])
        kexuan.erase (kexuan.find (x));
}
void dfs (int u, int tar, int lim)
{
    for (int i = lim; i <= 14; i ++ )
    {
        if ((a[u] >> i & 1) != (tar >> i & 1))
        {
            int na = a[u] ^ (1 << i);
            if (!pos[na])
                addans (u, na);
            else
            {
                dfs (pos[na], tar, i + 1);
                addans (u, na);
                break;
            }
        }
    }
}
signed main ()
{
    // freopen ("test.in", "r", stdin); freopen ("test.out", "w", stdout);
    ios::sync_with_stdio (0); cin.tie (0); cout.tie (0);
    cin >> n;
    for (int i = 1; i <= n; i ++ )
    {
        cin >> a[i];
        pos[a[i]] = i;
    }
    for (int i = 1; i <= n; i ++ )
    {
        cin >> b[i];
        mp[b[i]] = 1;
    }
    for (int i = 1; i <= n; i ++ )
    {
        if (!mp[a[i]])
            kexuan.insert (i);
    }
    for (int i = 1; i <= n; i ++ )
    {
        if (!pos[b[i]])
            dfs (*kexuan.begin (), b[i], 0);
    }
    cout << tot << endl;
    for (int i = 1; i <= tot; i ++ )
        cout << ans[i].x << " " << ans[i].y << endl;
    return 0;
}