洛谷 P1330 封锁阳光大学 二分图染色模板

裸的二分图染色模板,

由于求最少的河蟹,所以在每次重新更新颜色(dfs)的时候ans=ans+min(ans1,ans2)

不能到最后再统计颜色为1的有几个、颜色为0的有几个,因为此时并不能保证最优

var
        n,m,l,ans1,ans2,x,y:longint;
        ans                :longint;
        i                  :longint;
        last,co            :array[0..10010] of longint;
        other,len,pre      :array[0..200010] of longint;
       // b                  :boolean;
procedure connect(x,y:longint);
begin
   inc(l);
   pre[l]:=last[x];
   last[x]:=l;
   other[l]:=y;
end;

procedure dfs(x,t:longint);
var
        p,q:longint;
begin
   q:=last[x];
   t:=t xor 1;
   while (q<>0) do
   begin
      p:=other[q];
      if (co[p]=co[x]) then
      begin
         writeln('Impossible');halt;
      end else
      if (co[p]=-1) then
      begin
         co[p]:=t;
         if t=1 then inc(ans1) else inc(ans2);
         dfs(p,t);
      end;
      q:=pre[q];
   end;
end;

begin
   read(n,m);
   for i:=1 to m do
   begin
      read(x,y);
      connect(x,y);
      connect(y,x);
   end;
   for i:=1 to n do co[i]:=-1;

   for i:=1 to n do
    if co[i]=-1 then
    begin
       co[i]:=1;
       ans1:=1;ans2:=0;
       dfs(i,1);
       if ans2<ans1 then inc(ans,ans2)
        else inc(ans,ans1);
    end;

   writeln(ans); 
end.

——by Eirlys


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值