覆盖(染色算法)——史上最强解析

来源:互联网 发布:身份证照片软件 编辑:程序博客网 时间:2024/06/06 05:01
const dx:array[1..4] of longint=(1,0,-1,0);      dy:array[1..4] of longint=(0,1,0,-1);var teamx,teamy:array[1..100000] of longint;    map:array[0..200,0..200] of boolean;    n,m,x,y,k,w,b,i,j,ans:longint;function min(q,w:longint):longint;begin  if q<w then exit(q)         else exit(w);end;procedure bfs(x,y:longint);var f,r,xx,yy,i:longint;begin  fillchar(teamx,sizeof(teamx),0);  fillchar(teamy,sizeof(teamy),0);  //建造两个队列分别储存点的坐标值  f:=0; r:=1; teamx[r]:=x;//存储x  teamy[r]:=y;//存储y  w:=0; b:=0;  repeat    inc(f); x:=teamx[f]; y:=teamy[f];    if odd(x)=odd(y) then inc(w)                     else inc(b);//建造黑白相间的图,w用来记录白块数,b用来记录黑块数    for i:=1 to 4 do      begin        xx:=x+dx[i]; yy:=y+dy[i];        if not map[xx,yy] then//如果可以走的话          begin            inc(r); teamx[r]:=xx; teamy[r]:=yy;            map[xx,yy]:=true;          end;      end;  until f>=r;end;begin  readln(n,m); ans:=0;//读入数据长和宽  readln(k);  for i:=1 to k do//读入水塘位置    begin      readln(x,y);      map[x,y]:=true;//不能走的地方标记为true    end;  for i:=0 to m+1 do begin//对左右两侧加边    map[0,i]:=true;    map[n+1,i]:=true;  end;  for i:=0 to n+1 do begin//对上下两侧加边    map[i,0]:=true;    map[i,m+1]:=true;                end;//上述过程相当于把每个能走的方块拆成点的形式,然后建图深搜  for i:=1 to n do//枚举宽    for j:=1 to m do//枚举长      if not map[i,j] then//如果可以走的话        begin          bfs(i,j);//深搜开始          inc(ans,min(w,b));         end;  writeln(ans);end.
0 0
原创粉丝点击