main :-
	read_num(N),
	read_n_num_list(N, Jumps),
	findall(Cost, jump_cost(Jumps, Cost), CostList),
	min_list(CostList, MinCost),
	write(MinCost),
	nl,
	halt.

jump_cost(Jumps, C) :-
        jump(Jumps, Path),
        sum_list(Path, C).

jump([_], []).
jump([H1, H2|R], [NewH|L]) :-
        NewH is abs(H1 - H2),
        jump([H2|R], L).
jump([H1, _H2, H3|R], [NewH|L]) :-
        NewH is abs(H1 - H3),
        jump([H3|R], L).


read_n_num_list(Num, List) :-
	read_n_num_list_aux(Num, [], List),
	!.
read_n_num_list_aux(0, List, List).
read_n_num_list_aux(Num, Old, Accum) :-
	read_num(NewItem),
	NewNum is Num - 1,
	append(Old, [NewItem], NewList),
	read_n_num_list_aux(NewNum, NewList, Accum).

read_str(S) :-
        read_string(current_input, ' \n', '', _, S).

read_num(N) :-
	read_str(S),
	number_string(N, S).

:- main.
