题解:B4302 [蓝桥杯青少年组省赛 2024] 出现奇数次的数
rui_er
·
·
题解
约定记号 x\oplus y 表示 x 与 y 的 按位异或 ,即 C++ 中的 x ^ y 或 x xor y。
异或运算满足性质:
- 交换律,即 x\oplus y=y\oplus x。
- 结合律,即 (x\oplus y)\oplus z=x\oplus (y\oplus z)。
- 恒等律,即 x\oplus 0=0\oplus x=x。
- 归零律,即 x\oplus x=0。
设题目中的数列为 a。设 S=a_1\oplus a_2\oplus\cdots\oplus a_n,即 S 为所有元素的异或和。由以上性质,将出现偶数次的相等的数两两配对,它们的异或和为 0;将出现奇数次的数两两配对,除了若干对数的异或和为 0 以外,还会剩余一个数,因此它们的异或和为这个数本身。因此,S 的值为出现奇数次的这个数,即为答案。
例如样例中:
\begin{aligned}
S&=\text{\color{red}6}\oplus \text{\color{blue}2}\oplus \text{\color{orange}4}\oplus \text{\color{red}6}\oplus \text{\color{orange}4}\oplus \text{\color{blue}2}\oplus 6\\
&=(\text{\color{red}6}\oplus \text{\color{red}6})\oplus (\text{\color{blue}2}\oplus \text{\color{blue}2})\oplus
(\text{\color{orange}4}\oplus \text{\color{orange}4})\oplus 6\\
&=\text{\color{red}0}\oplus \text{\color{blue}0}\oplus \text{\color{orange}0}\oplus 6\\
&=6
\end{aligned}
可以得到正确答案。
时间复杂度 O(n)。
核心代码:
//By: OIer rui_er
const int N = 1e5 + 5;
int n, a[N];
cin >> n;
for(int i = 1; i <= n; ++i) cin >> a[i];
cout << accumulate(a + 1, a + 1 + n, 0, bit_xor<int>()) << endl;