首页 > 技术文章 > 洛谷P1330 封锁阳光大学

yu-xing 2019-03-31 17:21 原文

题意:给出n个点m条边的无向图 选出一些点覆盖所有边,使得选出的点互不相邻,且剩下的点互不相邻。求最少选出点数。

显然,当图中出现奇环则无解。用染色法进行判定(数据较大,dfs可能栈的深度过深,可以用BFS或并查集),当起点颜色确定后,若有解,则该图一定是二分图,染色方案唯一。染成黑白两种颜色后,取两种颜色中较小的点数作为答案。

注意原图可能不连通,逐一枚举起点BFS,否则只有40分...

code

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn=10005,maxm=200005;
queue<int> q;
int color[maxn],n,m,ans,Top=-1;
struct edge{
    #define New(p) p=&e[++Top]
    int to;edge *Nex;
}e[maxm],*head[maxn];
inline void add(int x,int y){
    edge *p;New(p);p->to = y;p->Nex = head[x];head[x] = p;
}
int BFS(int x){
    q.push(x);
    color[x]=1;
    int cnt1=0,cnt2=0;
    while(!q.empty()){
        int u=q.front();q.pop();
        if(color[u]==1) ++cnt1;
        else ++cnt2;
        for(edge *i=head[u];i!=NULL;i=i->Nex){
            if(!color[i->to]){
                color[i->to]=3-color[u];//染色 
                q.push(i->to); 
            }
            else if(color[i->to]==color[u]) return -1;
        }
    }
    return min(cnt1,cnt2);//取两种颜色中数量较少的 
} 
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1,x,y;i<=m;++i){
        scanf("%d%d",&x,&y);
        add(x,y);add(y,x);
    }
    for(int i=1;i<=n;++i){
        if(!color[i]){//注意 原图可能不连通 
            int now=BFS(i);//对每个联通块分别处理 
            if(now==-1){
                printf("Impossible");
                return 0;
            }
            else ans+=now;
        }
    }
    printf("%d",ans);
    return 0;
}

推荐阅读