B. Bitwise Reversion
Problem Statement
You are given three non-negative integers , and . Determine whether there exist three non-negative integers , and satisfying the following three conditions:
where denotes the bitwise AND operation.
Solution Explanation
The problem requires us to find if three non-negative integers exist, given the results of their pairwise bitwise AND operations.
Let’s analyze the constraints imposed by the bitwise AND operation on .
- The condition implies that for any bit position, if the bit is 1 in , it must also be 1 in both and .
- Similarly, implies that any bit set in must also be set in both and .
- And implies that any bit set in must also be set in both and .
From these observations, we can determine the minimum set of bits that must be active in .
- For , it must contain all the bits that are set in and all the bits that are set in . The smallest integer that satisfies this is .
- For , it must contain all the bits from and . The smallest integer is .
- For , it must contain all the bits from and . The smallest integer is .
This gives us a potential candidate solution. Let’s try constructing this way:
- Let
- Let
- Let
This construction gives us the “smallest” possible values for that could work. If any other integers form a valid solution, it must be that is a submask of , is a submask of , and is a submask of . However, adding more bits to (i.e., changing a 0 to a 1) can only cause the result of an AND operation to stay the same or change from 0 to 1. It can never change a 1 to a 0. This means if our minimal construction (a & b) results in a bit that is not in x, no larger value for a or b can fix it.
Therefore, if this minimal construction works, a solution exists. If it fails, no solution can exist. The strategy is to construct these candidate values for and then verify if they satisfy the original three equations.
The algorithm is:
- Calculate the candidate values:
a = x | z,b = x | y,c = y | z. - Check if they satisfy the conditions:
(a & b) == x(b & c) == y(c & a) == z
- If all three conditions are true, the answer is “YES”. Otherwise, it’s “NO”.
View Code
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
#define int long long
// #define mod 1000000007
#define N 500005
void solve() {
int x, y, z;
cin >> x >> y >> z;
int a = x | z;
int b = x | y;
int c = y | z;
if ((a & b) == x && (b & c) == y && (c & a) == z){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
#ifdef DEBUG
freopen("./input.txt", "r", stdin);
#endif
int t;
cin >> t;
while (t--) {
#ifdef DEBUG
static int test_num = 1;
cout << "test case: " << test_num++ << endl;
#endif
solve();
}
}