题解:CF2074C XOR and Triangle
思考过程
- 首先列出三角不等式:
\begin{cases} a + b > c \\ a + c > b \\ b + c > a \end{cases} - 这等价于:
\begin{cases} a + b > c \\ a - b < c \end{cases} - 在题目里面就是:
\begin{cases} x + y > x \oplus y \\ x - y < x \oplus y \end{cases} - 第一个式子等价于
x ,y 进行按位与运算后结果不为0 。 - 第二个式子等价于
x ,y 进行按位或运算后结果不为x 。 - 这样子,
y 只需要在x 二进制下最低的1 和最低的0 两位取1 ,其他位取0 即可。代码
//C #include <bits/stdc++.h> using namespace std; int t;
void solve(){ int x, tp, fa = 0, fb = 0, y; cin >> x; for(int i = 0; i <= 30; i ++){ if((x >> i) & 1) tp = i; } for(int i = 0; i <= tp; i ++){ if(!((x >> i) & 1)){ fa = 1; y = (1 << i); break; } } for(int i = 0; i <= tp; i ++){ if((x >> i) & 1){ fb = 1; y += (1 << i); break; } } if(x <= y || (!fa) || (!fb)) cout << "-1\n"; //记得特判 else cout << y << "\n"; }
int main(){ cin >> t; while(t --){ solve(); } return 0; }