P1330 封锁阳光大学

仔细审题, 冷静分析, 看到一句话:

当两只河蟹封锁了相邻的两个点时,他们会发生冲突

一条边必须且只能被一个点覆盖.

想到了什么? 二分图!

然后就可以愉快的码了.

需要注意的是, 这张图不一定联通, 所以每一个联通快的黑白染色数目要单独统计, 而不能一起统计.

正解:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 1e4 + 20;

int N, M;
vector<int> g[MAXN];
int col[MAXN];    bool flag = true;
int cnt[3];

bool dfs(int cur, int type){
    if(col[cur]){
        if(type != col[cur]) return flag = false;
        else return true;
    }
    col[cur] = type;
    for(int i = 0; i < (int) g[cur].size(); i++)
        if(!dfs(g[cur][i], type == 1 ? 2 : 1)) return false;
    ++cnt[type];
    return true;
}

int main()
{
    cin>>N>>M;
    for(int i = 1, u, v; i <= M; i++){
        scanf("%d%d", &u, &v);
        g[u].push_back(v), g[v].push_back(u);
    }
    int ans = 0;
    for(int i = 1; i <= N; i++) if(!col[i]) {
        cnt[2] = cnt[1] = 0; 
        if(!dfs(i, 1)){
            puts("Impossible"); return 0;
        }
        ans += min(cnt[1], cnt[2]);
    }

    printf("%d
", ans);
    return 0;
}

错误:

// luogu-judger-enable-o2
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 1e4 + 20;

int N, M;
vector<int> g[MAXN];
int col[MAXN];    bool flag = true;
int cnt[3];

bool dfs(int cur, int type){
    if(col[cur]){
        if(type != col[cur]) return flag = false;
        else return true;
    }
    col[cur] = type;
    for(int i = 0; i < (int) g[cur].size(); i++)
        dfs(g[cur][i], type == 1 ? 2 : 1);
    ++cnt[type];
    return true;
}

int main()
{
    cin>>N>>M;
    for(int i = 1, u, v; i <= M; i++){
        scanf("%d%d", &u, &v);
        g[u].push_back(v), g[v].push_back(u);
    }
    for(int i = 1; i <= N; i++) if(!col[i]) dfs(i, 1);
    if(!flag) puts("Impossible");
    else printf("%d
", min(cnt[1], cnt[2]));
    return 0;
}
原文地址:https://www.cnblogs.com/wsmrxc/p/9282205.html