View source with raw comments or as raw
    1:- module(weight_seq_tclp,_).    2
    3:- use_package(tabling).    4:- use_package(t_clpq).    5:- table weightAux/5.    6
    7:- include('select_instance.pl').
    8
    9test(T,W) :-
   10    abolish_all_tables,
   11    statistics(runtime,_), query([_,_,W]), statistics(runtime, [_|T]).
   12
   13query([InnerTree, Color, W]) :-
   14    max_total_weight(MaxW),
   15    W .=<. MaxW,
   16    weight_seq_tclp:num(Lenght),
   17    create(0, Lenght, L),
   18    permutation(L, List),
   19    weight(List, InnerTree, Color, W).
   20
   21weight([L1, L2|Tree], [innerLeftRight(1, L1, L2)|InnerTree], [innerColor(1, Color, WNode)|ColorTree], Weight) :-
   22    Weight .=. WNode + WMid,
   23    leafWeightCardinality(L1, W1, _),
   24    colorWeight(W1, L2, Color, WNode),
   25    weightAux(1, [WNode|Tree], InnerTree, ColorTree, WMid).
   26
   27 weightAux(N, [W1, L2|Tree], [innerLeftRight(N1, N, L2)|InnerTree], [innerColor(N1,Color, WNode)|ColorTree], Weight) :-
   28    N1 is N + 1,
   29    colorWeight(W1, L2, Color, WNode),
   30    weightAux(N1, [WNode|Tree], InnerTree, ColorTree, WMid),
   31    Weight is WNode + WMid.
   32
   33weightAux(_, [_Weight], [], [], 0).
   34
   35
   36colorWeight(W1, L2, Color, W) :-
   37    leafWeightCardinality(L2, W2, C2),
   38    G is W2 + C2,
   39    R is W1 + W2,
   40    B is W1 + C2,
   41    (
   42        G .=<. R, G .=<. B ->
   43        Color = green,
   44        W = G
   45    ;
   46        R .=<. B ->
   47        Color = red,
   48        W = R
   49    ;
   50        Color = blue,
   51        W = B
   52    ).
   53
   54permutation([], []).
   55
   56permutation(L, [T|Q]) :-
   57    select(T, L, L1),
   58    permutation(L1, Q).
   59
   60create(Max, Max, []).
   61create(N,   Max, [L|Ls]) :-
   62    N < Max,
   63    N1 is N + 1,
   64    atom_number(AN, N1),
   65    atom_concat(leaf, AN, L),
   66    create(N1, Max, Ls)