帮忙看看这个算法

hcwp2008 2014-05-09 03:29:16
unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Edit5: TEdit;
Edit6: TEdit;
Edit7: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
a :array of Integer;
implementation

{$R *.dfm}
{利用回溯法将一组数分成两组,每一组数各近似于该组数合计的一半}
procedure TForm1.Button1Click(Sender: TObject);
var
i,j,n,sum: Integer;
target: Double;
array1,array2:array of Integer;
tempTarget: Integer;
CloseValue,tempSub: Double;
tempValue: Integer;
Replaced: Boolean;
s,sp:string;
begin
n := 0;
s := Trim(Edit7.Text);
//Form1.Caption := IntToStr(Length(s)) ;
//计算数字的个数
for i := 0 to Length(s)-1 do
begin
if s[i]=',' then
n := n+1;
end;
SetLength(a,n+1);
i := 0;
n := 1;
j := 0;
sp := '';
while i<= Length(s) do
begin
{以','为节点把数分配到数组中}
if s[i]=',' then
begin
a[j] := StrToInt(Copy(s,n,i-n));
j := j+1;
n := i+1; //上一个','的数加1
end;
i := i+1;
end;
sum := 0;
for i := Low(a) to High(a) do
begin
sum := sum + a[i]; //计算各数字的和
//Form1.Caption := IntToStr(High(a))+'+'+ IntToStr(Low(a));
end;
target := sum / 2; //该组数和的一半
n := Length(a) div 2;
SetLength(array1,n);
SetLength(array2,n);
for i := 0 to n-1 do
begin
array1[i] := a[i]; //分两组,前一半赋值
array2[i] := a[i+n] //后一半赋值,所以加n
end;
while True do
begin
tempTarget := 0;
//求前一半的和
for i := 0 to n-1 do
begin
tempTarget := tempTarget + array1[i];
end;
CloseValue := target - tempTarget; //目标值(数的总和的一半)减去前一半的和
Replaced := False;
for i := 0 to n-1 do
begin
for j := 0 to n-1 do
begin
tempSub := array2[j] - array1[i];
if (tempSub < 0) and (CloseValue < 0)then
begin
tempSub := - tempSub;
CloseValue := - CloseValue;
end;
if (Abs(CloseValue - tempSub)< CloseValue) and (tempSub >= 0) then
begin
tempValue := array1[i];
array1[i] := array2[j];
array2[j] := tempValue;
Replaced := True;
Break;
end;
end;
if Replaced then Break;
end;
if not Replaced then Break;

end;
Edit3.Text := '';
Edit4.Text := '';
tempTarget := 0;
for i := 0 to n-1 do
begin
Edit3.Text := Edit3.Text + IntToStr(array1[i]) + '+';
Edit4.Text := Edit4.Text + IntToStr(array2[i]) + '+';
tempTarget := tempTarget + array1[i];
end;
Edit5.Text := IntToStr(tempTarget);
Edit6.Text := IntToStr(sum - tempTarget);
Edit1.Text := IntToStr(sum);
Edit2.Text := FloatToStr(target);
end;

end.
...全文
136 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
hcwp2008 2014-05-09
  • 打赏
  • 举报
回复
看不懂红色部份算法,尤其两个if条件 运行图

16,747

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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