您的位置:首页 > 其它

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

2016-11-15 23:55 232 查看
裸的二分图染色模板,

由于求最少的河蟹,所以在每次重新更新颜色(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  模板 二分图