使用 C++ 查詢集合中自反關係的數量


在本文中,我們將解釋查詢集合中自反關係數量的方法。在這個問題中,我們給定一個數字 n,在一個包含 n 個自然數的集合上,我們必須確定自反關係的數量。

自反關係 - 集合 A 中的關係如果對於每個屬於集合 A 的 'a',(a, a) 都屬於 R,則稱為自反關係。例如 -

Input : x = 1
Output : 1
Explanation : set = { 1 }, reflexive relations on A * A :
{ { 1 } }

Input : x = 2
Output : 4
Explanation : set = { 1,2 }, reflexive relations on A * A :
   { ( 1, 1 ) , ( 2, 2 ) }
   { ( 1, 1 ), ( 2, 2 ), ( 1, 2 ) }
   { ( 1, 1 ), ( 2, 2 ), ( 1, 2 ), ( 2, 1 ) }
   { ( 1, 1 ), ( 2, 2 ), ( 2, 1 ) }

因此,如果 (a, a) ∈ R ∀ a ∈ A,則關係是自反的。

查詢解決方案的方法

集合元素的自反關係數量可以用公式 2n(n-1) 計算。這個通用公式是透過計算整數的自反關係的數量生成的。

示例

#include <iostream>
using namespace std;
int countReflexive(int n){
    int ans = 1 << (n*n - n);
    return ans;
}
int main(){
    int n ;
     cin >> n ; // taking input n from the user using std cin.
    int result = countReflexive(n); // calling function to calculate number of reflexive relations
    cout << "Number of reflexive relations on set: " << result ; // printing the answer
    return 0;
}

輸出

Number of reflexive relations on set: 1

上述程式的解釋

這個程式很容易理解,因為我們只是從使用者那裡獲取輸入並將其放入公式 2n(n-1) 中,我們使用左移 "<" 運算子來計算公式,此程式碼的時間複雜度為 O(1),隨著 n 大小增加而變慢。

結論

在本文中,我們解決了一個問題,即查詢集合中自反關係的數量。我們討論了使用公式計算自反關係數量的簡單方法,該公式由數學家推導得出。

我們還學習了針對此問題的 C++ 程式,透過該程式我們找到了時間複雜度為 O(1) 的解決方案。我們可以使用 C、Java、Python 等其他語言編寫相同的程式。

更新於:2021年11月24日

435 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.