您的位置:首页 > 其它

hihoCoder#1121 二分图一•二分图判定

2015-03-21 23:32 232 查看
原题地址

图的遍历,深度优先

向来对图的数据结构就练习的比较少,这种题目还是挺好的。

代码:

#include <iostream>
#include <vector>
#include <set>

using namespace std;

bool dye(vector<vector<int> > &graph, vector<int> &nodes, int i) {
for (auto j : graph[i]) {
if (nodes[j] == 0) {
nodes[j] = -1 * nodes[i];
if (!dye(graph, nodes, j))
return false;
}
else if (nodes[j] == nodes[i])
return false;
}

return true;
}

int main() {
int T, N, M;

cin >> T;
while (T--) {
cin >> N >> M;
vector<vector<int> > graph(N, vector<int>());
for (int i = 0; i < M; i++) {
int a, b;
cin >> a >> b;
graph[a - 1].push_back(b - 1);
graph[b - 1].push_back(a - 1);
}

vector<int> nodes(N, 0);
bool ok = true;
for (int i = 0; i < N; i++) {
if (nodes[i] == 0 && !graph[i].empty()) {
nodes[i] = 1;
if (!dye(graph, nodes, i)) {
ok = false;
break;
}
}
}
cout << (ok ? "Correct" : "Wrong") << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: