Cod sursa(job #372971)

Utilizator philipPhilip philip Data 12 decembrie 2009 12:31:03
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator fpc Status done
Runda Arhiva educationala Marime 1.53 kb
var n,m,e,i,x,y,min,flux,j:longint;
    cap,f:array[0..20001,0..20001] of shortint;
    c,t:array[0..20001] of integer;
    viz:array[0..20001] of boolean;

function bf:boolean;
  var p,u,k,i:longint;
  begin
    for i:=1 to n+m+1 do viz[i]:=false;
    c[1]:=0;
    p:=1;
    u:=1;
    while p<=u do begin
      k:=c[p];
      for i:=1 to n+m+1 do
        if not viz[i] and (cap[k,i]-f[k,i]>0) then begin
          inc(u);
          c[u]:=i;
          t[i]:=k;
          viz[i]:=true;
        end;
      inc(p);
    end;
    if viz[n+m+1] then bf:=true else bf:=false;
  end;

begin
  assign(input,'cuplaj.in');
  reset(input);
  assign(output,'cuplaj.out');
  rewrite(output);
  readln(n,m,e);
  for i:=1 to e do begin
    readln(x,y);
    cap[x,n+y]:=1;
  end;
  for i:=1 to n do cap[0,i]:=1;
  for i:=n+1 to n+m do cap[i,n+m+1]:=1;
  while bf do
    for i:=1 to n+m do
      if cap[i,n+m+1]-f[i,n+m+1]>0 then begin
        j:=i;
        min:=1;
        while j<>0 do begin
          if cap[t[j],j]-f[t[j],j]<1 then
            min:=0;
            j:=t[j];
        end;
        if min<>0 then begin
        j:=i;
        while j<>0 do begin
          f[t[j],j]:=f[t[j],j]+1;
          f[j,t[j]]:=f[j,t[j]]-1;
          j:=t[j];
        end;
        f[i,n+m+1]:=f[i,n+m+1]+1;
        f[n+m+1,i]:=f[n+m+1,i]-1;
        flux:=flux+1;
        end;
      end;
  writeln(flux);
  for i:=1 to n do
    for j:=n+1 to n+m do
      if f[i,j]=1 then writeln(i,' ',j-n);
  close(input);
  close(output);
end.