C++ 程序,查找 XOR 运算结果与求和结果相同的 l-r 对数
假设我们有一个 N 元素的数组 A。需要查找满足 A[l] XOR A[l+1] XOR ... XOR A[r-1] XOR A[r] = A[l] + A[l+1] + ... A[r] 的整数对 l 和 r 的数量。
因此,如果输入类似 A = [2, 5, 4, 6],则输出将为 5,因为对应对 (1,1)、(2,2)、(3,3)、(4,4) 和 (1,2)。
步骤
要解决此问题,需要按照以下步骤进行 -
n := size of A Define some arrays of size (n + 1) each, a, s and sx for initialize i := 1, when i <= n, update (increase i by 1), do: a[i] := A[i - 1] s[i] := s[i - 1] + a[i] sx[i] := sx[i - 1] XOR a[i] res := 0 for initialize l := 1, when l <= n, update (increase l by 1), do: bg := l, en = n, r = l while bg <= en, do: mi := (bg + en) / 2 if s[mi] - s[l - 1] is same as (sx[mi] XOR sx[l - 1]), then: r := mi bg := mi + 1 Otherwise en := mi - 1 res := res + (r - l + 1) return res
示例
下面让我们看看以下实现以加深理解 -
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A){ int n = A.size(); vector<int> a(n + 1), s(n + 1), sx(n + 1); for (int i = 1; i <= n; i++){ a[i] = A[i - 1]; s[i] = s[i - 1] + a[i]; sx[i] = sx[i - 1] ^ a[i]; } int res = 0; for (int l = 1; l <= n; l++){ int bg = l, en = n, r = l; while (bg <= en){ int mi = (bg + en) / 2; if (s[mi] - s[l - 1] == (sx[mi] ^ sx[l - 1])){ r = mi; bg = mi + 1; } else en = mi - 1; } res += (r - l + 1); } return res; } int main(){ vector<int> A = { 2, 5, 4, 6 }; cout << solve(A) << endl; }
输入
{ 2, 5, 4, 6 }
输出
5
广告