int main() { int t; scanf("%d",&t); while(t--) { int E,i,j; scanf("%d %d",&V,&E); int G[V][V]; int a,b; for(i=0;i<V;i++) for(j=0;j<V;j++) G[i][j]=0; while(E--) { scanf("%d %d",&a,&b); a--; b--; G[a][b]=1; G[b][a]=1; } isBipartite(G, 0) ? printf("YES\n") : printf("NO\n"); } return 0; }
bool isBipartite(int root, Colors* verticesColors) { auto edge = edges[root]; while (edge != nullptr) { if (verticesColors[edge->verticeTo] == Colors::Undefined) { if (verticesColors[root] == Colors::Red) { verticesColors[edge->verticeTo] = Colors::Black; } else { verticesColors[edge->verticeTo] = Colors::Red; } if (isBipartite(edge->verticeTo, verticesColors) == false) { return false; } edge = edge->next; } else if (verticesColors[edge->verticeTo] == verticesColors[root]) { return false; } } return true; }
int main(int main, char* argv[]) { auto graph = new Graph(4); graph->addEdge(1, 2); graph->addEdge(1, 3); graph->addEdge(1, 4); graph->addEdge(2, 4); std::cout << "Graph should not be bipartite: " << graph->isBipartite() << std::endl; graph = new Graph(5); graph->addEdge(1, 2); graph->addEdge(1, 3); graph->addEdge(2, 4); graph->addEdge(4, 5); std::cout << "Graph should be bipartite: " << graph->isBipartite() << std::endl; }
void BicoloringAnalizer::analizeGraphs(string fileName) { int numOfVertices; int numOfEdges; int vertex; int adjacentVertex; std::ifstream input; input.exceptions(std::ios_base::failbit | std::ios_base::badbit); try { input.open(fileName, std::ios_base::in); input >> numOfVertices; while (numOfVertices != 0) { if (numOfVertices < 2 || numOfVertices > 199) { input.close(); throw std::runtime_error("Wrong number of nodes. Must be \"1 < nodes < 200\"\n"); } input >> numOfEdges; if (numOfEdges < 1) { input.close(); throw std::runtime_error("Wrong data in file.\n"); } graph.clear(); graph.resize(numOfVertices); for (int i = 0; i < numOfEdges; i++) { input >> vertex >> adjacentVertex; if (vertex >= 0 && vertex < numOfVertices && adjacentVertex >= 0 && adjacentVertex < numOfVertices) graph[vertex].push_back(adjacentVertex); else { input.close(); throw std::runtime_error("Wrong vertex label. Must be \"0 <= vertex_label < numOfVertices\"\n"); } } if (isBipartite(numOfVertices)) std::cout << "BICOLORABLE." << std::endl; else std::cout << "NOT BICOLORABLE." << std::endl; input >> numOfVertices; } } catch (std::ios_base::failure) { std::cerr << "Error reading file: "; input.close(); throw; } input.close(); }
bool isBipartite() { Colors *verticesColors = (Colors*)malloc((numberOfVertices + 1)*sizeof(Colors)); memset(verticesColors, 0, (numberOfVertices + 1)*sizeof(Colors)); for (auto i = 1; i < numberOfVertices; ++i) { if (verticesColors[i] == Colors::Undefined) { verticesColors[i] = Colors::Red; if (isBipartite(i, verticesColors) == false) { return false; } } } return true; }
int main() { std::vector<std::vector<int>> test = {{1,2}, {0,2}, {0,1}}; std::cout << "Is bipartite? " << isBipartite(test) << std::endl; return 0; }