跳到正文

题解

题解:B4302 [蓝桥杯青少年组省赛 2024] 出现奇数次的数

rui_er约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
1
题目
B4302

版本

  1. v1当前

约定记号 x⊕yx\oplus y 表示 xx 与 yy 的 按位异或 ,即 C++ 中的 x ^ y 或 x xor y。

异或运算满足性质:

  • 交换律,即 x⊕y=y⊕xx\oplus y=y\oplus x。
  • 结合律,即 (x⊕y)⊕z=x⊕(y⊕z)(x\oplus y)\oplus z=x\oplus (y\oplus z)。
  • 恒等律,即 x⊕0=0⊕x=xx\oplus 0=0\oplus x=x。
  • 归零律,即 x⊕x=0x\oplus x=0。

设题目中的数列为 aa。设 S=a1⊕a2⊕⋯⊕anS=a_1\oplus a_2\oplus\cdots\oplus a_n,即 SS 为所有元素的异或和。由以上性质,将出现偶数次的相等的数两两配对,它们的异或和为 00;将出现奇数次的数两两配对,除了若干对数的异或和为 00 以外,还会剩余一个数,因此它们的异或和为这个数本身。因此,SS 的值为出现奇数次的这个数,即为答案。

例如样例中:

S=6⊕2⊕4⊕6⊕4⊕2⊕6=(6⊕6)⊕(2⊕2)⊕(4⊕4)⊕6=0⊕0⊕0⊕6=6\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)O(n)。

核心代码:

C++
//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;
原文