POJ 1325(2部图匹配)

2部图匹配,不能考虑0


Program P1325;
var
   n,m,k,i,j:longint;
   p,x,y,level:longint;
   map,f,list:array[-1..300,-1..300] of longint;
   d,e:array[-1..300] of longint;
   queue:array[1..300] of longint;
   b:array[-1..300] of boolean;
function min(a,b:longint):longint;
begin
   if a<b then exit(a) else exit(b);
end;
function max(a,b:longint):longint;
begin
   if a>b then exit(a) else exit(b);
end;

procedure dijstra;
var
   h,t,i:longint;
begin
   fillchar(d,sizeof(d),0);
   fillchar(queue,sizeof(queue),0);
   fillchar(b,sizeof(b),false);
   queue[1]:=n+m;
   b[n+m]:=true;
   h:=1;
   t:=1;
   while h<=t do
   begin
      for i:=-1 to n+m-1 do
      begin
         if (map[i,queue[h]]>0) then
            if (not(b[i])) then
         begin
            inc(t);
            queue[t]:=i;
            b[i]:=true;
            d[i]:=d[queue[h]]+1;
         end;
      end;
      inc(h);
   end;
   d[-1]:=n+m+2+1;
end;
procedure push(i,j:longint);
var
   flow:longint;
begin
   flow:=min(e[i],map[i,j]-f[i,j]);

   if (e[j]=0) and (j>-1) and (j<n+m) then
   begin
      inc(list[d[j],0]);
      list[d[j],list[d[j],0]]:=j;
      level:=max(level,d[j]);
   end;

   dec(e[i],flow);
   inc(e[j],flow);
   inc(f[i,j],flow);
   f[j,i]:=-f[i,j];

end;
procedure relable(i:longint);
var
   j,minj:longint;
begin
   minj:=maxlongint;
   for j:=-1 to n+m do
      if (map[i,j]-f[i,j]>0) and (b[j]) then minj:=min(minj,d[j]);
   d[i]:=minj+1;

   level:=d[i];
   inc(list[level,0]);
   list[level,1]:=i;
end;
Procedure hllp;
var
   i,j,flow:longint;
begin
   dijstra;

   level:=0;
   for i:=0 to n-1 do
      if b[i] then
      begin
         e[i]:=1;
         f[-1,i]:=1;
         f[i,-1]:=-1;


         inc(list[d[i],0]);
         list[d[i],list[d[i],0]]:=i;
         level:=max(level,d[i]);
      end;
   while (level>0) do
   begin
      i:=list[level,list[level,0]];
      dec(list[level,0]);
      while (level>0) and (list[level,0]=0) do dec(level);

      for j:=-1 to n+m do
         if (d[i]=d[j]+1) and (map[i,j]-f[i,j]>0) and (b[j]) then
         begin
            push(i,j);

            if e[i]=0 then break;
         end;
      if e[i]>0 then relable(i);

   end;

end;
begin
   read(n);
   while (n>0) do
   begin
      fillchar(list,sizeof(list),0);
      fillchar(e,sizeof(e),0);
      fillchar(f,sizeof(f),0);

      read(m,k);
      fillchar(map,sizeof(map),0);
      for i:=1 to k do
      begin
         read(p,x,y);
         if (x=0) or (y=0) then continue;
         map[x,n+y]:=1;
      end;
      for i:=0 to n-1 do map[-1,i]:=1;
      for i:=n to n+m-1 do map[i,n+m]:=1;
      hllp;
      writeln(e[n+m]);

      read(n);

   end;
end.


你可能感兴趣的:(POJ 1325(2部图匹配))