【作题笔记】P1330 封锁阳光大学

读题易得:对于有边的两个点 \(u,v\) ,能且仅能其中一点对这条边进行封锁。node

什么意思呢?假设给这张图上的点进行染色,那么对于上述的两个点 \(u,v\)\(u,v\) 必须异色(理解这一点很重要)。ios

那么,也就是说,在这张图上,若是要把这张图“彻底封锁”且两只河蟹不能封锁相邻的两个点,换而言之,把链接一条边的两个点染色,这两个点是异色的,那么整张图上无非也就这两种颜色,答案无非也就是这两种颜色中数目较少那一种的数目。数组

注意到存在无解的状况,那么是么时候无解呢?想一下,遍历这张图,那么确定会遇到作过的点。把咱们本身想成河蟹,那么重复来到这时至关于给这个点从新染色。 若是咱们携带的“颜料”和上一只河蟹是同样的,那么至关于什么都不作;但若是不一样,至关于对这个点从新封锁,这就产生了冲突。因此,这时不合法,返回 0 。不然返回 1 。spa

请注意:这个图可能不是联通的,因此须要设 vis 数组,判断某个点有没有用过,去遍历全部的小连通图。code

参考代码:get

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int n,m,vis[4000010],c[3],head[4000010],tot,_color[4000010];
//_color[u]表明第 u 个点的颜色
//c[]记录两种颜色的数量
struct node
{
    int to,nxt;
};
node G[400010];

inline int read()
{
    int s=0,w=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')s=s*10+ch-'0',ch=getchar();
    return s*w;
}

inline void add(int u,int v)
{
    G[++tot]=(node){v,head[u]},head[u]=tot;
    G[++tot]=(node){u,head[v]},head[v]=tot;
}

int dfs(int u,int cor)
{
    if(vis[u])
    {
        if(_color[u]==cor)return 1;
        return 0;
    }
    vis[u]=1;
    c[_color[u]=cor]++;
    int can_do=1;
    for(int i=head[u];i&&can_do;i=G[i].nxt)can_do=can_do&&dfs(G[i].to,1-cor);
    return can_do;
}

int main()
{
    int ans;
    n=read(),m=read();
    for(int i=1;i<=m;i++){int u=read(),v=read();add(u,v);}
    for(int i=1;i<=n;i++)
    {
        if(vis[i])continue;
        c[0]=c[1]=0;
        if(dfs(i,0)==0){cout<<"Impossible"<<endl;return 0;}
        ans+=min(c[0],c[1]); //注意,这里是加上
    }
    cout<<ans<<endl;
    return 0;
}
相关文章
相关标签/搜索