C++ 色数-Groetzsch图

C++ 色数-Groetzsch图,c++,algorithm,chromatic,C++,Algorithm,Chromatic,好的,我正在做一个学校的任务,写一个程序,从包含顶点数和图形邻接矩阵的文本文件中计算图形的色数,如下所示: 8 0 1 0 1 1 0 0 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 0 以下是我的节目: #include <algorithm> #include <climits> #in

好的,我正在做一个学校的任务,写一个程序,从包含顶点数和图形邻接矩阵的文本文件中计算图形的色数,如下所示:

8

0 1 0 1 1 0 0 1
1 0 1 0 0 0 0 0
0 1 0 1 0 0 0 0
1 0 1 0 0 0 0 0
1 0 0 0 0 1 0 0
0 0 0 0 1 0 1 0
0 0 0 0 0 1 0 1
1 0 0 0 0 0 1 0
以下是我的节目:

#include <algorithm>
#include <climits>
#include <fstream>
#include <iostream>
#include <vector>

#define MAX 512

using namespace std;

bool adjMat[MAX][MAX]; 

int chromaticNum(int n) {
   int chromaticRet = 1; // return value, chromatic number

   vector<int> colors(n, INT_MAX); // color for every vertex
   colors[0] = 0;                  

   // iterating through every vertex except 0 as that one already has a color
   for (int i = 1; i < n; i++) {

      int color = 0; // current/first color
      for (int j = 0; j < n; j++) {   
         if (adjMat[j][i] == 1) {     // 1 = vertices are adjacent
            if (colors[j] == color) { // if the adjacent vertex is that color we change the color to  the next one
               ++color;              
            }
         }
      }
      bool colorAdded = true;
      for (int d = 0; d < n; d++) { // checking if this color has already been used
         if (colors[d] == color) {
            colorAdded = false;
         }
      }
      colors[i] = color;
      if (colorAdded) {
         ++chromaticRet;
      }
   }

   return chromaticRet;
}

int main() {

   string fileName;
   cin >> fileName;
   int i, j;
   ifstream stream;
   stream.open(fileName.c_str());
   int n = 0;

   if (stream.is_open()) {

      stream >> n;
      stream.ignore(1, '\n');


      for (i = 0; i < n; i++) {
         for (j = 0; j < n; j++) {
            stream >> adjMat[i][j];
         }
      }
      cout << "Chromatic number: " << chromaticNum(n) << endl;

   } else {
      cout << "File not found";
   }
   stream.close();

   return 0;
}



这段代码应该只在适当的时间内适用于较小的图形,所以我不想让它更省时,我想知道为什么它适用于其他图形,但不适用于此图形。

\define MAX 512
不必使用预处理器宏。更好:
constexpr int MAX=512您的问题是,当您增加当前顶点的颜色中间循环时,您必须对照新颜色检查所有节点,但代码只检查其余节点。修正这个问题会为您的输入产生预期的4,但我不认为这个贪婪算法适用于所有的图。正如您可能知道的,图着色就像您建议的算法一样。即使您为这个特定的graph类修复了它,也有可能很快会遇到它失败的其他族。
#define MAX 512
不必使用预处理器宏。更好:
constexpr int MAX=512您的问题是,当您增加当前顶点的颜色中间循环时,您必须对照新颜色检查所有节点,但代码只检查其余节点。修正这个问题会为您的输入产生预期的4,但我不认为这个贪婪算法适用于所有的图。正如您可能知道的,图着色就像您建议的算法一样。即使您为这个特定的graph类修复了它,也有可能很快会遇到它失败的其他族。
11

0 1 1 0 0 0 0 1 0 0 1
1 0 0 1 0 0 1 0 0 1 0
1 0 0 0 1 0 1 0 1 0 0
0 1 0 0 1 0 0 0 1 0 1
0 0 1 1 0 0 0 1 0 1 0
0 0 0 0 0 0 1 1 1 1 1 
0 1 1 0 0 1 0 0 0 0 0
1 0 0 0 1 1 0 0 0 0 0 
0 0 1 1 0 1 0 0 0 0 0
0 1 0 0 1 1 0 0 0 0 0 
1 0 0 1 0 1 0 0 0 0 0