CF2187B
我们直接在原来的 与 上操作,使得操作后 且与原来的差最小。记原来的 为 ,原来的 为 。
我们注意到如果 ,则 与 在二进制上没有共同位。因此如果第 个二进制位 与 都有,我们需要在 或者 中减去 。令被操作过的 的最大值为 。 无论选择 或者 ,对于 的值没有影响,这启发我们保持 或者 不变。
我们现在讨论 不变的情况。现在我们可以让 或者 。
对于情况 ,我们让 尽可能加上一些数,在 的前提下,我们需要确保此时加的 满足 。为了防止 ,我们只要找到 与 同为 的位 加上 即可。
对于情况 ,我们发现一定会加上某个比 大的 来抵消减去的部分,为了让 尽可能小,我们把比 低的位全部赋为 ,第 位赋为 ,其他位不变即可。
不变的情况同理,取最小值即可。
时间复杂度:在处理 时我们使用 枚举的同时,赋 时使用 次循环。故时间复杂度为单组 。
代码:
#include <bits/stdc++.h>
using namespace std;
int T,now = 0,dc = 1,x,y;
string a,b;
namespace DoubleQLzn
{
void init()
{
return ;
}
pair<int,int> calc(int x,int y)
{
int ma = -1;
a.clear(),b.clear();
int x2 = x,y2 = y;
while (x != 0)
{
a.push_back(x % 2 + '0');
x /= 2;
}
while (y != 0)
{
b.push_back(y % 2 + '0');
y /= 2;
}
x = x2,y = y2;
for (int i = 0;i < min(a.size(),b.size());i++)
{
if (a[i] + b[i] == 98)
{
x = x - (1 << i);
a[i] = '0';
ma = max(ma,i);
}
}
int now = x;
for (int i = 0;i <= ma;i++)
{
if (a[i] + b[i] == 96) now = now + (1 << i);
}
for (int i = ma + 1;i <= 30;i++)
{
if (i >= b.size() || b[i] == '0')
{
if (a[i] == '1') continue;
int xx = x;
for (int j = 0;j <= i;j++)
{
if (a[j] == '1') xx = xx - (1 << j);
}
xx = xx + (1 << i);
if (abs(xx - x2) < abs(now - x2)) now = xx;
}
}
return make_pair(now,y);
}
pair<int,int> minn(pair<int,int> a,pair<int,int> b)
{
int c1 = abs(a.first - x) + abs(a.second - y);
int c2 = abs(b.second - x) + abs(b.first - y);
if (c1 < c2) return a;
else return make_pair(b.second,b.first);
}
void solve()
{
cin >> x >> y;
pair<int,int> ans = minn(calc(x,y),calc(y,x));
cout << ans.first << ' ' << ans.second << '\n';
}
}
int main()
{
if (dc == 0) T = 1;
else cin >> T;
while (T--)
{
DoubleQLzn::init();
DoubleQLzn::solve();
}
return 0;
}