- :- use_module(library(chr)).
- :- chr_option(optimize, full).
- :- chr_type list(T) ---> []; [T|list(T)].
- :- chr_type edge ---> edge(int,int,int).
- :- chr_type heap ---> edge-list(heap).
- :- chr_constraint
- heap(+heap), tail(+list(heap)), pop, top(+edge),
- matrix(+int,+list(list(any))),
- row(+int,+int,+list(any)),
- current_weight(+int),
- count(+int),
- group(+list(int),+int),
- answer(+int),
- problem107.
- problem107 <=> current_weight(0), data(X), matrix(1,X), count(0), pop.
- data(X) :- csv_read_file('network.txt',Rows), maplist(term_list,Rows,X).
- term_list(T,X) :- T =.. [_|X].
- heap(M-L), heap(N-L1) <=> comp(M,N) | heap(M-[N-L1|L]).
- tail([H|T]) <=> heap(H), tail(T).
- tail([]) <=> true.
- pop, heap(A-L) <=> tail(L), top(A).
- comp(edge(_,_,M),edge(_,_,N)) :- M =< N.
- matrix(N,[H|T]) <=> row(N,1,H), N1 is N+1, matrix(N1,T).
- matrix(_,[]) <=> true.
- row(M,N,[-|T]) <=> N1 is N+1, row(M,N1,T).
- row(M,N,[_|T]) <=> M >= N | N1 is N+1, row(M,N1,T).
- current_weight(X), row(M,N,[H|T])
- <=> heap(edge(M,N,H)-[]), X1 is X+H, current_weight(X1), N1 is N+1, row(M,N1,T).
- row(_,_,[]) <=> true.
- count(39) \ heap(_) <=> true.
- count(39) \ current_weight(M), group(_,N) <=> X is M-N, answer(X).
- pop, count(39) <=> true.
- group(L,_) \ top(edge(A,B,_))
- <=> member(A,L), member(B,L) | pop.
- group(L,X), group(L1,Y), count(N), top(edge(A,B,Z))
- <=> (member(A,L), member(B,L1); member(B,L), member(A,L1))
- | ord_union(L,L1,L2), X1 is X+Y+Z, group(L2,X1), N1 is N+1, count(N1), pop.
- group(L,X), count(N), top(edge(A,B,Y))
- <=> member(A,L)
- | ord_add_element(L,B,L1), X1 is X+Y, group(L1,X1), N1 is N+1, count(N1), pop.
- group(L,X), count(N), top(edge(A,B,Y))
- <=> member(B,L)
- | ord_add_element(L,A,L1), X1 is X+Y, group(L1,X1), N1 is N+1, count(N1), pop.
- count(N), top(edge(A,B,X))
- <=> list_to_ord_set([A,B],L), group(L,X), N1 is N+1, count(N1), pop.