题解:CF2187B Shortest Statement Ever
DoubleQLzn
·
2026-02-12 22:50:13
·
题解
CF2187B
我们直接在原来的 x 与 y 上操作,使得操作后 x\ \&\ y=0 且与原来的差最小。记原来的 x 为 x2 ,原来的 y 为 y2 。
我们注意到如果 x\ \& \ y=0 ,则 x 与 y 在二进制上没有共同位。因此如果第 i 个二进制位 x 与 y 都有,我们需要在 x 或者 y 中减去 2^i 。令被操作过的 i 的最大值为 ma 。 无论选择 x 或者 y ,对于 |x-x2|+|y-y2| 的值没有影响 ,这启发我们保持 x 或者 y 不变。
我们现在讨论 y 不变的情况。现在我们可以让 x<x2 或者 x>x2 。
对于情况 x<x2 ,我们让 x 尽可能加上一些数,在 x<x2 的前提下,我们需要确保此时加的 2^i 满足 i<ma 。为了防止 x\ \&\ y\neq0 ,我们只要找到 x2 与 y2 同为 0 的位 i 加上 2^i 即可。
对于情况 x>x2 ,我们发现一定会加上某个比 ma 大的 i 来抵消减去的部分,为了让 x 尽可能小,我们把比 i 低的位全部赋为 0 ,第 i 位赋为 1 ,其他位不变即可。
时间复杂度:在处理 $x>x2$ 时我们使用 $O(\log V)$ 枚举的同时,赋 $0$ 时使用 $O(\log V)$ 次循环。故时间复杂度为单组 $O(\log^2V)$。
代码:
```cpp
#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;
}
```