求教一个算法,急等帮助

sharklee 2001-11-22 11:44:44
小刚假期同妈妈一起去书店,他选中了n本书,每本书的单价为:p1,p2,p3...pn元(均为整数)。不巧的是,妈妈只带了s(为整数)元钱,不够买这n本书(即:s<p1+p2+p3+...+pn)。妈妈同意将这s元全部用来买书,也就是小刚要从n本书中选出m本,使得这m本的价格和刚好等于s,即p1+p2+p3+...+pn=s,请你编程序将所有满足这一条件的i1,i2,i3,...im依次打印出来。
...全文
98 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
王集鹄 2001-11-23
  • 打赏
  • 举报
回复
//用组合就可以了
//借用一下二进制

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

uses
Math;

const
cScaleChar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function IntToDigit(mNumber: Integer; mScale: Byte; mLength: Integer = 0): string;
var
I, J: Integer;
begin
Result := '';
I := mNumber;
while (I >= mScale) and (mScale > 1) do begin
J := I mod mScale;
I := I div mScale;
Result := cScaleChar[J + 1] + Result;
end;
Result := cScaleChar[I + 1] + Result;
if mLength > 0 then
for I := 1 to mLength - Length(Result) do
Result := '0' + Result;
end; { IntToDigit }

function DigitToInt(mDigit: string; mScale: Byte): Integer;
var
I: Byte;
L: Integer;
begin
Result := 0;
L := Length(mDigit);
for I := 1 to L do
Result := Result + (Pos(mDigit[L - I + 1], cScaleChar) - 1) *
Trunc(IntPower(mScale, I - 1));
end; { DigitToInt }

function f(mPrices: array of Real; mMoney: Real): string;
var
I, J: Integer;
L: Integer;
S, C: string;
T: Real;
begin
L := Length(mPrices);
with TStringList.Create do try
for I := 0 to Trunc(IntPower(2, L)) - 1 do begin
S := IntToDigit(I, 2, L);
T := 0;
C := '';
for J := 1 to L do if S[J] = '1' then begin
T := T + mPrices[J - 1];
C := C + ',' + FloatToStr(mPrices[J - 1]);
end;
System.Delete(C, 1, 1);
if T = mMoney then
Add(S + ':' + C);
end;
Result := Text;
finally
Free;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Text := f([1, 2, 3, 4, 5, 6, 7], 20);
end;

end.
superatom 2001-11-22
  • 打赏
  • 举报
回复
1、首先将大于S的书排除出去;
2、用循环把书价进行组合,找出符合条件的组合
sharklee 2001-11-22
  • 打赏
  • 举报
回复
我还是不太明白,你能不能讲的详细一点。
baddy 2001-11-22
  • 打赏
  • 举报
回复
做几个数组,将价格、书名、标志对应存入,当满足时就读数组不就行了吗?
知足常乐 2001-11-22
  • 打赏
  • 举报
回复
关键是效率问题
scripting 2001-11-22
  • 打赏
  • 举报
回复
用一个递归调用可以
开始: 一个n整数数组N和一个整数m
后来变成: 一个n-1整数数组和一个整数i-N[0]
后来 n-2 i-N[0]-N[1]
。。。。。。。
当元素没有了、当i-???<=0了判断出口
这个就像汉诺塔,挺有意思。

byrybye 2001-11-22
  • 打赏
  • 举报
回复
好象挺难,
如果要效率的话
sharklee 2001-11-22
  • 打赏
  • 举报
回复
楼上的道理我也知道,但我需要一个行之有效的算法

5,927

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧