Codeforces Round #360 (Div. 1) A. NP-Hard Problem(二分图染色)

题目链接:点击打开链接

思路:根据题目描述, 就是找两个不相交点集使得对于每一条边至少有一个顶点在点集中, 那么显然对于每条边必须是一个点在A集合, 一个点在B集合, 即二分图染色裸题。

WA了一次, 因为有可能存在好几个连通图。

细节参见代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <bitset>
#include <cstdlib>
#include <cmath>
#include <set>
#include <list>
#include <deque>
#include <map>
#include <queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;
const int mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
// & 0x7FFFFFFF
const int seed = 131;
const ll INF64 = ll(1e18);
const int maxn = 1e5 + 10;
int T,n,m, color[maxn];
vector<int> g[maxn];
bool ok(int u) {
    int len = g[u].size();
    for(int i = 0; i < len; i++) {
        int v = g[u][i];
        if(color[v] == color[u]) return false;
        if(!color[v]) {
            color[v] = 3 - color[u];
            if(!ok(v)) return false;
        }
    }
    return true;
}
int u, v;
int main() {
    scanf("%d%d", &n, &m);
    for(int i = 0; i < m; i++) {
        scanf("%d%d", &u, &v);
        g[u].push_back(v);
        g[v].push_back(u);
    }
    bool flage = true;
    for(int i = 1; i <= n; i++) {
        if(!color[i]) {
            color[i] = 1;
            if(!ok(i)) {
                flage = false; break;
            }
        }
    }
    if(!flage) {
        printf("-1\n");
        return 0;
    }
    vector<int> ans1, ans2;
    for(int i = 1; i <= n; i++) {

        if(color[i] == 1) ans1.push_back(i);
        else ans2.push_back(i);

    }
    int len = ans1.size();
    printf("%d\n", len);
    for(int i = 0; i < len; i++) {
        printf("%d%c", ans1[i], i == len-1 ? '\n' : ' ');
    }
    len = ans2.size();
    printf("%d\n", len);
    for(int i = 0; i < len; i++) {
        printf("%d%c", ans2[i], i == len-1 ? '\n' : ' ');
    }
    return 0;
}


你可能感兴趣的:(codeforces,ACM-ICPC,二分图染色)