【发布时间】:2021-12-04 17:50:13
【问题描述】:
我很困惑为什么我的代码会产生错误的输出。如果每个节点还没有被访问过,我会尝试为每个节点执行 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
【问题讨论】:
-
vector<int> graph[n + 1];在符合标准的 C++ 中无效。为什么不vector<vector<int>> graph(n + 1)? -
你为什么使用
bits/stdc++.h?那只会鼓励你写草率的代码。 -
不要使用神秘和简短的变量名。您的程序代码应该是自记录的。此外,您的代码混合了惯用的 C 和 C++ 风格,并且您正在改变全局状态。这里有很多改进...
-
请提供示例输入、该输入的预期输出以及您得到的结果。
-
另外,“我很困惑为什么我的代码产生错误的输出。” 到底是什么意思?你的代码产生了什么输出,你期望它产生什么?
标签: c++ algorithm data-structures