跳到正文

题解

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

legendcn666约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年6月10日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 4 分钟
题目
P10258

版本

  1. v2当前
  2. v1

题意:

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

题解:

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

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

C++
# 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;
}
原文