[英]BFS algorithm for checking bipartite graph
我很困惑为什么我的代码会产生错误的输出。如果每个节点还没有被访问过,我正在尝试为每个节点做 bfs,并尝试访问它的 adj 节点。 任何人都可以帮我找到问题吗? 这是我的代码:-
#include <bits/stdc++.h>
using namespace std;
int p = 1;
int ans[200005] = {-1};
bool bfs(vector<int> graph[], int x, int ans[])
{
queue<int> q;
q.push(x);
ans[x] = 1;
while (!q.empty())
{
int f = q.front();
q.pop();
for (auto it : graph[f])
{
if (ans[it] == -1)
ans[it] = 1 - ans[f], q.push(it);
else if (ans[it] == ans[f])
return true;
}
}
return false;
}
signed main()
{
int n, m;
cin >> n >> m;
vector<int> graph[n + 1];
for (int i = 1, a, b; i <= m; i++)
{
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for (int i = 1; i <= n; i++)
{
if (ans[i] == -1)
{
if (bfs(graph, i, ans))
p = 0;
}
}
if (!p)
cout << "IMPOSSIBLE";
else
{
for (int i = 1; i <= n; i++)
{
cout << ans[i] + 1 << ' ';
}
}
}
输入 :-
5 3
1 2
1 3
4 5
预期输出:-
1 2 2 1 2
收到的输出:-
1 1 1 1 1
你的算法很好
C 数组初始化不会从只包含 1 个元素的花括号列表初始化程序初始化整个数组,除了它是 0。
int arr1[5] = {-1}; // -1, 0, 0, 0, 0
int arr1[5] = {0}; // 0, 0, 0, 0, 0
见https://stackoverflow.com/a/1065800/10911830
这是固定代码,压缩了主要功能只是为了不浪费屏幕空间:
#include <vector> // for input
#include <iostream> // for debugging
#include <queue> // for bfs
#include <algorithm> // for std::fill_n
using namespace std;
bool bfs(vector<int> graph[], int x, int ans[])
{
queue<int> q;
q.push(x);
ans[x] = 1;
while (!q.empty())
{
int f = q.front();
q.pop();
for (auto it : graph[f])
{
if (ans[it] == -1){
ans[it] = 1 - ans[f];
q.push(it);
}
else if (ans[it] == ans[f])
return true;
}
}
return false;
}
int main()
{
int p = 1;
const int ANS_MAX = 200005;
int ans[ANS_MAX];
std::fill_n(ans, ANS_MAX , -1); // 1. array initialization
int n, m;
cin >> n >> m;
vector<int> graph[n + 1];
for (int i = 1, a, b; i <= m; i++)
{
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for (int i = 1; i <= n; i++)
if (ans[i] == -1 && bfs(graph, i, ans)) p = 0;
if (!p) cout << "IMPOSSIBLE";
else for (int i = 1; i <= n; i++) cout << ans[i] + 1 << ' ';
}
我没有使用任何其他输入对其进行测试,因此可能存在一些错误,但至少现在主要问题已得到修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.