PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

使用C++找到XOR为零的独特三元组的数量

王林
王林 转载
2023-09-08 18:09:05 775浏览

使用C++找到XOR为零的独特三元组的数量

在本文中,我们将讨论在给定的唯一数字数组中计算唯一三元组(x,y,z)的数量,其中它们的异或为0。因此,三元组应该是唯一的,其中所有三个元素都是唯一的,并且将计算所有三元组的组合,例如−

Input : arr[ ] = { 5, 6, 7, 1, 3 }
Output : 2
Explanation : triplets are { 5, 6, 3 } and { 6, 7, 1 } whose XOR is zero.

Input : arr[ ] = { 3, 6, 8, 1, 5, 4 , 12}
Output : 3
Explanation : Triplets are { 3, 6, 5 }, { 1, 5, 4 } and { 4, 8, 12 } whose XOR is zero.

寻找解决方案的方法

我们知道相同值的异或运算结果总是零。因此,我们要寻找独特的三元组,可以采用一种乐观的方法,即找到数组中两个值的异或结果,并将结果存储起来,然后在数组中搜索等于该结果的值。此外,结果的值不应与任何一对值相等。请查看

示例

#include <bits/stdc++.h>
using namespace std;

int main () {
   int arr[] = { 3, 6, 8, 1, 5, 4, 12 };
   int n = sizeof (arr) / sizeof (arr[0]);
   int result;
   // count variable to keep count of pairs.
   int count = 0;
   // creating a set to store unique numbers .
   unordered_set < int >values;
   // inserting values in set.
   for (int i = 0; i < n; i++)
      values.insert (arr[i]);


   // traverse for all pairs to calculate XOR.
   for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) { // finding xor of i, j pair.
         int XR = arr[i] ^ arr[j];

         // checking if XOR value of pair present in array
         // and value should not be in pairs.
         if (values.find (XR) != values.end () && XR != arr[i] &&
            XR != arr[j])
            count++;
      }

   }
   // storing result
   result = count / 3;
   cout << "Number of unique triplets : " << result;
   return 0;
}

输出

Number of unique triplets : 3

上述代码的解释

  • 创建一个unordered_set values来存储给定数组中的唯一数字。
  • 使用for()循环通过values.insert(arr[i])将值插入集合中。
  • 使用两个嵌套循环遍历所有的数对,并计算它们的异或值。
  • 然后,在数组中搜索异或值,并在值在数组中而不在数对中时增加计数。
  • 将结果存储为count / 3,这样就可以计算出三个组合的三元组数,而我们需要的是唯一的三元组。

结论

本文讨论了如何找到具有异或值为0的三元组的数量;我们讨论了一种乐观的方法来找到唯一的三元组。我们还讨论了用C++解决这个问题的程序。然而,我们可以用其他编程语言如Java、C、Python等来编写这个程序。希望本文对您有所帮助。

以上就是使用C++找到XOR为零的独特三元组的数量的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除