#base.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Ensure that every goal jet can be pressurized

openPath(J,J) :-
	jet(J), goal(J).
openPath(J,N1) :-
	jet(J), goal(J),
	openPath(J,N2),
	link(N1,N2,V),
	not stuck(V).

canPressurize(J) :-
	jet(J), goal(J),
	tank(T), full(T),
	openPath(J,T).

:- not canPressurize(J), jet(J), goal(J).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Find the shortest path that feeds each goal jet


reachable(J,J,0) :-
	jet(J), goal(J).

pressurePath(J,T,0) :-
	jet(J), goal(J),
	tank(T), full(T),
	reachable(J,T,0).

#cumulative s.
reachable(J,N1,s) :-
	jet(J), goal(J),
	reachable(J,N2,s-1),
	link(N1,N2,V),
	not stuck(V).

pressurePath(J,T,S) :-
	S<=s,
	jet(J), goal(J),
	tank(T), full(T),
	reachable(J,T,S).

-orphan(J,s) :-
	jet(J), goal(J),
	S<=s,
	pressurePath(J,T,S).

orphan(J,s) :-
	jet(J), goal(J),
	not -orphan(J,s).

orphans(s) :-
	jet(J), goal(J),
	orphan(J,s).

all_done(s) :-
	not orphans(s).

shortestPath(J,SL) :-
	all_done(s),
	jet(J), goal(J),
	-orphan(J,s),
	SL=#min[ pressurePath(J,T,L)=L : tank(T) : full(T) ].

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Determine which valves must be opened
%% (must handle the case in which there are
%% multiple best paths)
%%
poss_use_valve(J,N,V,S-1) :-
	all_done(s),
	jet(J), goal(J),
	shortestPath(J,S),
	tank(T), full(T),
	reachable(J,T,S),
	reachable(J,N,S-1),
	link(T,N,V).

poss_use_valve(J,N2,V2,S-1) :-
	all_done(s),
	jet(J), goal(J),
	poss_use_valve(J,N1,V1,S),
	reachable(J,N2,S-1),
	link(N1,N2,V2).

1{ use_valve(J,N,V,0) : poss_use_valve(J,N,V,0) }1 :-
	all_done(s),
	jet(J), goal(J).

1{ use_valve(J,N2,V2,S+1) : poss_use_valve(J,N2,V2,S+1) : link(N2,N1,V1) : not tank(N2) }1 :-
	all_done(s),
	jet(J), goal(J),
	shortestPath(J,MS),
	use_valve(J,N1,V1,S),
%	link(N2,N1,V1),
	S<MS-1.

n_prevActions(J,NP) :-
	all_done(s),
	goal(J),
	NP=#sum[ shortestPath(J1,N)=N : goal(J1) : J1 < J ].

switchon(V,S-LS-1+NP) :-
	all_done(s),
	goal(J),
	shortestPath(J,S),
	n_prevActions(J,NP),
	use_valve(J,N,V,LS).

#volatile s.
:- orphans(s).

% in case the instance follows...
#base.
