使用C++查詢XOR值為零的唯一三元組的數量


在本文中,我們將討論如何在一個給定的唯一數字陣列中計算唯一三元組 (x, y, z) 的數量,其中它們的XOR值為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.

尋找解決方案的方法

我們知道相同值的XOR總是為零。所以我們找到唯一的三元組,可以使用一種樂觀的方法,即找到陣列中兩個值的XOR並存儲結果,然後在陣列中搜索等於該結果的值。此外,結果值不應等於對中的任何值。尋找:

示例

#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])`將值插入集合。
  • 使用兩個巢狀迴圈遍歷所有對並計算它們的XOR值。
  • 然後,在陣列中搜索XOR值,如果在陣列中找到該值且不在對中,則遞增計數。
  • 將結果儲存為`count / 3`,這將計算三元組的三種組合,而我們需要唯一的三元組。

結論

本文討論瞭如何查詢XOR值為0的三元組的數量;我們討論了一種查詢唯一三元組的樂觀方法。我們還討論了用於解決該問題的C++程式。但是,我們可以使用其他程式語言(如Java、C、Python等)編寫此程式。我們希望您覺得本文有所幫助。

更新於:2021年11月26日

419 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告