Xin chào mọi người, em đang học về đồ thị. Một đồ thị gọi là Bipartite nếu đồ thị có thể chia thành 2 phần mà mỗi cạnh của đỉnh phần này nối đến một đỉnh của phần kia. Nghĩa là nếu tô màu một đỉnh là màu trắng(true) thì các đỉnh có cạnh nối với nó tiếp theo sẽ là màu đen(false).
Input: Cho đồ thị vô hướng có n đỉnh và m cạnh(dòng đầu). m dòng tiếp theo là các đỉnh nối với nhau.
Dữ liệu được tính toán lại thành các đỉnh -> 0 1 2 3 để thuận tiện lưu trữ trong vector.
0 1 3 2
1 0 2
2 1 0
3 0
Bài làm của em dùng BFS để giải nhưng không biết sai gì nữa. Mong các anh xem và gợi ý giúp em. Em xin cảm ơn nhiều.
// Week3Problem2.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
bool BFS(vector<vector<int>> adj, vector<bool> &color, vector<bool> &haveColor,vector<bool> &visited, queue<int> & queue, int &curr)
{
visited[curr] = true;
haveColor[curr] = true;
queue.pop();
for (int i = 0; i < adj[curr].size(); i++)
{
int neighbour = adj[curr][i];
if (visited[neighbour] == true)
{
if (color[curr] == color[neighbour])
return false;
continue;
}
if (haveColor[neighbour] == true && color[curr] == color[neighbour])
return false;
queue.push(neighbour);
color[neighbour] = !color[curr];
haveColor[neighbour] = true;
}
return true;
}
int bipartite(vector<vector<int> > &adj) {
//write your code here
queue<int> elementQue;
elementQue.push(0);
vector<bool> color(adj.size());
vector<bool> haveColor(adj.size());
vector<bool> visited(adj.size());
while (!elementQue.empty())
{
int curr = elementQue.front();
if (visited[curr] == true)
continue;
if (BFS(adj, color, haveColor, visited, elementQue, curr) == false)
return 0;
}
return 1;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int> > adj(n, vector<int>());
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
cout << bipartite(adj);
}

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?