CodeForces 687A NP-Hard Problem 二分图入门题

判断所给的图是否是二分图,如果是,输出各自的点。

用染色法 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
", col[i].size());
        for (int v : col[i]) {
            printf("%d ", v + 1);
        }
        puts("");
    }
}
原文地址:https://www.cnblogs.com/hznumqf/p/13328894.html