2

您有 5、10、20、50、100 的硬币,
其重量分别为 2g、3g、10g、25g、50g。你的钱包很弱,所以你不能超过 391 克的重量。你只能在里面放 3 个相同价值的硬币。你能说一下你钱包的最大价值是多少吗?

询问 :::change([(Five,Ten,Twenty,Fifty,Hundred),W,S])

range(I,I,[I]).
range(I,K,[I|L]) :-             
    I < K,      
    I1 is I + 1,    
    range(I1,K,L).

coin(X,L) :-
    range(0,3,L1),
    member(X,L1).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

change([(Five,Ten,Twenty,Fifty,Hundred),W,S]) :- 
    coin(Five,L),
    coin(Ten,L),
    coin(Twenty,L),
    coin(Fifty,L),
    coin(Hundred,L),
    W1 = 50*Hundred + 25*Fifty + 10*Twenty +3*Ten+ 2*Five,
    S1 = 5*Five+ 10*Ten+ 20*Twenty + 50*Fifty + 100*Hundred,
    W1 < 391,
    W is W1,
    S is S1,
    maximum(S1).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
maximum(S1) :-
    S is S1,
    threshold(S),
    not( S1 < S).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

threshold(S1) :-
    M is S1,
    not( M < 451).
4

2 回答 2

3

使用并简单地运行以下查询:

:- 使用模块(库(clpfd))。

?- [百,五十,二十,十,五] ins 0..3,
   重量#=< 391,
   重量#=   50*10 + 25*50 + 10*20 + 3*10 + 2*5,
   值  #= 100*Hundred + 50*50 + 20*Twenty + 10*Ten + 5*Five,
   标注([max(Value)], [Hundred,50,Twenty,10,Five])。
百 = 3,五十 = 3,二十 = 3,十 = 3,五 = 3,价值 = 555,重量 = 270;
百 = 3,五十 = 3,二十 = 3,十 = 3,五 = 2,价值 = 550,重量 = 268;
...
于 2016-05-08T12:20:39.913 回答
0

由库(聚合)执行的“生成和测试”:

change(S) :-
    aggregate(max(V), P^W^(purse(P, W, V), W < 391), S).

purse(P, W, V) :-
    length(P, 5),
    maplist(between(0, 3), P),
    scalar(P, [2,3,10,25,50], W),
    scalar(P, [5,10,20,50,100], V).

scalar(Vs, Fs, S) :-
    foldl([V,F,V0,U]>>(U is V0+V*F), Vs, Fs, 0, S).

scalar/3 有点过度设计,如果您使用库(clpfd) ,建议您查看scalar_product /4

于 2016-05-10T10:20:07.810 回答