您好,欢迎访问一九零五行业门户网

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

在本文中,我们将讨论在给定的唯一数字数组中计算唯一三元组(x,y,z)的数量,其中它们的异或为0。因此,三元组应该是唯一的,其中所有三个元素都是唯一的,并且将计算所有三元组的组合,例如−
input : arr[ ] = { 5, 6, 7, 1, 3 }output : 2explanation : triplets are { 5, 6, 3 } and { 6, 7, 1 } whose xor is zero.input : arr[ ] = { 3, 6, 8, 1, 5, 4 , 12}output : 3explanation : 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为零的独特三元组的数量的详细内容。
其它类似信息

推荐信息