封锁阳光大学

判断这个图是否是2分图
注意在无法联通的两个独立的块中,要单独判断1还是-1的点少。

#include <cstdio>
#include <iostream>
using namespace std;
int cnt,n,m;
int head[99999],net[200001],to[200001];
int f[99999];
int flag=1; 
int ans;
int ans1;
int ans2;
void add(int x,int y)
{
    cnt++;
    to[cnt]=y;
    net[cnt]=head[x];
    head[x]=cnt;
}
void dfs(int x)
{
    if(flag==0) return;
    for(int i=head[x];i;i=net[i])
    {
        int tmp=to[i];
        if(f[x]==f[tmp]) 
        {
            flag=0;
            return;//冲突
        }
        if(!f[tmp])
        {
            if(f[x]==-1) 
            {
                ans1++;
                f[tmp]=1;
            } 
            else
            {
                f[tmp]=-1;
                ans2++;
            }
          dfs(tmp);
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);

    for(int i=1;i<=m;i++)
    {
        int x,y;

        scanf("%d%d",&x,&y);

        add(x,y);
        add(y,x);
    }

    for(int i=1;i<=n;i++)
    if(!f[i]&&flag==1)
    {
        ans1=1;//1的点数
        ans2=0;//-1的点数
        f[i]=1;
        dfs(i); 

        ans+=min(ans1,ans2);//最小值更新答案
    }


    if(flag==0) printf("Impossible");//冲突的话输出impossible
    else printf("%d",ans);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值