裸的二分图染色模板,
由于求最少的河蟹,所以在每次重新更新颜色(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