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