在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.