最小费用最大流模板

向总等编写的《奥赛经典·提高篇》上所给出的基本模板有误,现在把正确的模板贴上来。

Program MinCostMaxFlow;//By_Thispoet

Var

	c,f,cost				:Array[0..100,0..100]of Longint;

	a,b,ct					:Array[0..100]of Longint;

	ans						:Longint;

	i,j,k,m,n,p,q			:Longint;

	seq						:Array[1..10000]of Longint;

	h,t						:Longint;

	v						:Array[0..100]of Boolean;

	

Function Min(i,j:Longint):Longint;

begin

	if i<j then exit(i);exit(j);

end;

	

	

BEGIN



	readln(n,m);

	for i:=1 to m do

		begin

			read(j,k);

			readln(c[j,k],cost[j,k]);

		end;



	Repeat



		fillchar(v,sizeof(v),0);

		fillchar(ct,sizeof(ct),127);

		ct[0]:=0;

		v[0]:=true;

		a[0]:=-1;b[0]:=maxlongint;

		h:=0;t:=1;seq[1]:=0;

		while h<t do

			begin

				inc(h);k:=seq[h];

				for i:=1 to n+1 do

					if (f[k,i]<c[k,i])and(c[k,i]>0)and(ct[i]>ct[k]+cost[k,i])then

						begin

							inc(t);seq[t]:=i;

							a[i]:=k;b[i]:=Min(b[k],c[k,i]-f[k,i]);

							ct[i]:=ct[k]+cost[k,i];

							v[i]:=true;

						end else

							if (c[i,k]>0)and(f[i,k]>0)and(ct[i]>ct[k]-cost[i,k])then

								begin

									inc(t);seq[t]:=i;

									a[i]:=k;b[i]:=Min(b[k],f[i,k]);

									ct[i]:=ct[k]-cost[i,k];

									v[i]:=true;

								end;

			end;

		if v[n+1] then

			begin

				i:=n+1;

				while a[i]<>-1 do

					begin

						if (c[i,a[i]]>0)and(f[i,a[i]]>0) then

							begin

								dec(f[i,a[i]],b[n+1]);

								dec(ans,cost[i,a[i]]*b[n+1]);

							end else

								begin

									inc(f[a[i],i],b[n+1]);

									inc(ans,b[n+1]*cost[a[i],i]);

								end;

						i:=a[i];

					end;

			end;

		

	Until not v[n+1];

	

	writeln(ans);

	

END.

你可能感兴趣的:(最大流)