#hide.
#show altdepot/2.
#show costs/1.

% calculate the number of depots
depots(X) :- X = #count{ depot(DN,DK) }.

% get the closest depot for a restaurant
serves(RN,Dist) :- restaurant(RN,RK), Dist = #min [ depot(DN,DK) = #abs(DK-RK) ].

% get possible distances
dist(D) :- restaurant(RN1,RK1), restaurant(RN2,RK2), D=#abs(RK1-RK2).

% each restaurant may be an alternative depot
X { altdepot(RN,RK) : restaurant(RN,RK) } X :- depots(X).

% get the closest alternative depot for a restaurant
altserves(RN,Dist) :- restaurant(RN,RK), Dist = #min [ altdepot(DN,DK) = #abs(DK-RK) ].

% calculate the costs for the initial depots
costs(C) :- C = #sum[ serves(RN,Dist) : serves(RN,Dist) = Dist ].

% fail if we have not found a better solution
:- costs(C), C [ altserves(RN,Dist)=Dist : restaurant(RN,RK) : dist(Dist) ].
