CodeForces 687A NP-Hard Problem 二分圖入門題
阿新 • • 發佈:2020-07-17
判斷所給的圖是否是二分圖,如果是,輸出各自的點。
用染色法 DFS一遍即可 O(N + M)
vector<int> col[2]; vector<int> e[maxn]; int vis[maxn]; bool dfs(int v, int color) { vis[v] = color; col[color - 1].push_back(v); for (int u : e[v]) { if (!vis[u] && dfs(u, 3 - color)) return 1; if (vis[u] != 3- color) return 1; } return 0; } int main() { int n, m; int x, y; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d%d", &x, &y); e[x - 1].push_back(y - 1); e[y - 1].push_back(x - 1); } for (int i = 0; i < n; i++) {if (!vis[i]) { if (e[i].empty()) continue; if (dfs(i, 2)) { puts("-1"); return 0; } } } for (int i = 0; i < 2; i++) { printf("%d\n", col[i].size()); for (int v : col[i]) { printf("%d ", v + 1); } puts(""); } }