跳到正文

题解

CF1790E Vlad and a Pair of Numbers 题解:恒等式秒了

灵茶山艾府约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年12月30日
收录
2025年12月12日
更新
2026年11月12日
篇幅
约 3 分钟
获赞
33
题目
CF1790E

版本

  1. v1当前

对于二进制加法,a+ba+b 可以拆分 axor⁡ba\operatorname{xor} b 和两个 aand⁡ba\operatorname{and} b,即

a+b=(axor⁡b)+2⋅(aand⁡b)a+b = (a\operatorname{xor} b) + 2\cdot (a\operatorname{and} b)

结合题目给的公式

a+b=2⋅(axor⁡b)a+b = 2\cdot (a\operatorname{xor} b)

得

aand⁡b=axor⁡b2a\operatorname{and} b = \dfrac{a\operatorname{xor} b}{2}

如果 axor⁡ba\operatorname{xor} b 是奇数,或者 (axor⁡b)and⁡ (aand⁡b)≠0(a\operatorname{xor} b) \operatorname{and}\ (a\operatorname{and} b) \ne 0,那么无解。后者是因为 axor⁡ba\operatorname{xor} b 中的 11 说明在这个比特位上必定一个是 00 另一个是 11,and⁡\operatorname{and} 结果必定是 00,所以 axor⁡ba\operatorname{xor} b 和 aand⁡ba\operatorname{and} b 在同一个比特位上不可能都是 11,所以 (axor⁡b)and⁡ (aand⁡b)=0(a\operatorname{xor} b) \operatorname{and}\ (a\operatorname{and} b) = 0 恒成立。从集合的角度上来说就是 axor⁡ba\operatorname{xor} b 和 aand⁡ba\operatorname{and} b 不相交。

现在 aand⁡ba\operatorname{and} b 和 axor⁡ba\operatorname{xor} b 都知道了,可以构造出一组解了。

由于 aand⁡ba\operatorname{and} b 中的 11 在 aa 和 bb 中都有,而 axor⁡ba\operatorname{xor} b 中的 11 要么在 aa 中,要么在 bb 中,不妨全部给 aa,得

{a=(axor⁡b)or⁡ (aand⁡b)=(axor⁡b)+(aand⁡b)=3(axor⁡b)2b=aand⁡b=axor⁡b2\begin{cases} a = (a\operatorname{xor} b) \operatorname{or}\ (a\operatorname{and} b) = (a\operatorname{xor} b) + (a\operatorname{and} b) = \dfrac{3(a\operatorname{xor} b)}{2}\\ b = a\operatorname{and} b = \dfrac{a\operatorname{xor} b}{2} \end{cases}
Go
package main
import("bufio";."fmt";"os")

func main() {
	in := bufio.NewReader(os.Stdin)
	var T, xor int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &xor)
		and := xor >> 1
		if xor&1 > 0 || xor&and > 0 {
			Println(-1)
		} else {
			Println(xor|and, and)
		}
	}
}

时间复杂度:O(1)\mathcal{O}(1)。

欢迎关注 B站@灵茶山艾府

原文
存档评论3 条抓取于