在C++中查詢無向圖是否包含給定大小的獨立集


概念

針對給定的無向圖,驗證它是否包含大小為l的獨立集。如果存在大小為l的獨立集,則列印“Yes”,否則列印“No”。需要注意的是,圖中的獨立集定義為一組頂點,這些頂點之間沒有直接連線。

輸入

L = 4,
graph = [[1, 0, 1, 0, 0],
[0, 1, 1, 0, 0],[1, 1, 1, 1, 1],
[0, 0, 1, 1, 0],[0, 0, 1, 0, 1]];

輸出

Yes

上圖包含大小為4的獨立集(頂點0、1、3、4之間沒有直接連線)。因此輸出為“Yes”。

輸入

L = 4,
graph =[[1, 1, 1, 0, 0],[1, 1, 1, 0, 0],[1, 1, 1, 1, 1],[0, 0, 1, 1, 0],[0, 0, 1, 0, 1]];

輸出

No

在上圖中,該圖不包含大小為4的獨立集。因此輸出為“No”。

方法

  • 首先,將變數sol初始化為布林值False。
  • 確定給定圖中大小為L的所有可能的頂點集。
  • 如果找到大小為l的獨立集,則將sol的值更改為True並返回。
  • 否則繼續檢查其他可能的集合。
  • 最後,如果sol為True,則列印“Yes”,否則列印“No”。

示例

 線上演示

// C++ code to check if a given graph
// contains an independent set of size k
#include <bits/stdc++.h>
using namespace std;
// Shows function prototype
bool check1(int[][5], vector<int>&, int);
// Shows function to construct a set of given size l
bool func(int graph1[][5], vector<int>&arr1,
int l, int index1, bool sol1[]){
   // Verify if the selected set is independent or not.
   // Used to change the value of sol to True and return
   // if it is independent
      if (l == 0){
         if (check1(graph1, arr1, arr1.size())){
            sol1[0] = true;
            return true;
         }
      }
      else{
         // Now set of size l can be formed even if we don't
         // include the vertex at current index.
         if (index1 >= l){
            vector<int> newvec(arr1.begin(), arr1.end());
            newvec.push_back(index1);
            return (func(graph1, newvec, l - 1,
            index1 - 1, sol1) or
            func(graph1, arr1, l, index1 - 1, sol1));
         }
            // Now set of size l cannot be formed if we don't
         // include the vertex at current index.
         else{
            arr1.push_back(index1);
            return func(graph1, arr1, l - 1,
            index1 - 1, sol1);
         }
      }
   }
   // Shows function to verify if the given set is
   // independent or not
   // arr --> set of size l (contains the
   // index of included vertex)
   bool check1(int graph1[][5], vector<int>&arr1, int n1){
      // Verify if each vertex is connected to any other
         // vertex in the set or not
      for (int i = 0; i < n1; i++)
         for (int j = i + 1; j < n1; j++)
            if (graph1[arr1[i]][arr1[j]] == 1)
            return false;
      return true;
}
// Driver Code
int main(){
   int graph1[][5] = {{1, 0, 1, 0, 0},{0, 1, 1, 0, 0},{1, 1, 1, 1, 1},{0, 0, 1, 1, 0},
      {0, 0, 1, 0, 1}};
      int l = 4;
      vector<int> arr1; // Empty set
      bool sol1[] = {false};
      int n1 = sizeof(graph1) /
      sizeof(graph1[0]);
      func(graph1, arr1, l, n1 - 1, sol1);
      if (sol1[0])
         cout << "Yes" << endl;
      else
         cout << "No" << endl;
      return 0;
}

輸出

Yes

更新於:2020年7月24日

瀏覽量100次

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.