D. ConstructOR
D. ConstructOR
You are given three integers , , and . Your task is to find any integer which satisfies all of the following conditions, or determine that no such integers exist:
- ;
- is divisible by ;
- is divisible by .
Here, denotes the bitwise OR operation.
Input
Each test contains multiple test cases. The first line of input contains one integer — the number of test cases.
Each test case consists of one line, containing three integers , , and .
Output
For each test case print one integer. If there exists an integer which satisfies all of the conditions from the statement, print . Otherwise, print .
If there are multiple solutions, you may print any of them.
Example
input
8 12 39 5 6 8 14 100 200 200 3 4 6 2 2 2 18 27 3 420 666 69 987654321 123456789 999999999
output
18 14 -1 -1 0 11 25599 184470016815529983
Note
In the first test case, is one of the possible solutions, since and , both of which are multiples of .
In the second test case, is one of the possible solutions, since , which is a multiple of .
In the third and fourth test cases, we can show that there are no solutions.
解题思路
首先先确定无解的情况,对于根据求出其二进制下末尾的个数,假设为。如果或在二进制下末尾的个数小于,那么一定无解。这是因为含有因子,而或以及按位或后的结果都不可能含有因子,因此无解。
下面给出一种答案的构造方案,让,同时也是的倍数,这样至少可以保证和能被整除(下面再证明一定满足)。
由于,因此在第到第位中,如果或的第位为,那么的第为也应该要为,这样就可以保证。
那么如何保证是的倍数呢?当的第位要变成时,我们直接让加上的倍,即加上。等价于把左移位,这意味着的最低位的从第位左移到了第位,而此时的第位为,因此加上后第位就变成了,同时这样也保证了始终是的倍数。
下面来证明按照上面的构造方法得到的一定是满足。考虑最糟糕的情况:
AC代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef long long LL; 5 6 int lowbit(LL x) { 7 return x & -x; 8 } 9 10 void solve() { 11 LL a, b, d; 12 scanf("%lld %lld %lld", &a, &b, &d); 13 LL ret = 0; 14 if (lowbit(a) < lowbit(d) || lowbit(b) < lowbit(d)) { // a或b末尾0的个数小于d末尾0的个数 15 ret = -1; 16 } 17 else { 18 int k = log2(lowbit(d)); // d末尾0的个数 19 a |= b; 20 for (int i = k; i < 30; i++) { 21 // 如果a或b的第i位为1,并且此时x的第i位为0 22 if ((a >> i & 1) && (ret >> i & 1) == 0) ret += d << i - k; // 答案加上d * 2^(i-k) 23 } 24 } 25 printf("%lld\n", ret); 26 } 27 28 int main() { 29 int t; 30 scanf("%d", &t); 31 while (t--) { 32 solve(); 33 } 34 35 return 0; 36 }
参考资料
Codeforces Round #833 (Div. 2) A - D:https://zhuanlan.zhihu.com/p/582927038
Codeforces Round #833 (Div. 2) A-D.md:https://www.cnblogs.com/BlankYang/p/16885937.html
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/16893690.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效