?? unit2.pas
字號:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, Buttons,IdGlobal,Math;
//自己加進了delphi自帶的兩個庫單元
type
TForm2 = class(TForm)
StringGrid1: TStringGrid;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
uses unit1; //調用unit1的數據
procedure TForm2.BitBtn1Click(Sender: TObject);
var i,j,k:Integer;
bins:string;
//中間變量,存放整型轉化為二進制的結果
temp:Boolean;//協助判斷
hangzhi:real; //協助判斷是否驗證了所有的約束條件
zuiyouzhi:real;//目標函數最優值
n:Integer;//最優解的個數
begin
meijucishu:=1;
for j:=1 to VarNum do
meijucishu:=meijucishu*2;
//計算枚舉次數2的n次方次,n代表變量個數
StringGrid1.ColCount:=VarNum+3;
StringGrid1.RowCount:=meijucishu+1;
//根據需要設置,文本框的行和列
for j:=1 to VarNum do
StringGrid1.Cells[j,0]:='x'+IntToStr(j);
StringGrid1.Cells[VarNum+1,0]:='函數值';
StringGrid1.Cells[VarNum+2,0]:='判斷';
for i:=1 to meijucishu do
StringGrid1.Cells[0,i]:='枚舉 '+IntToStr(i);
//控制結果顯示界面
z:=nil;
biaoshi:=nil;
SetLength(z,meijucishu);//動態設置數組長度,存放目標函數值
SetLength(biaoshi,meijucishu);
//動態設置數組長度,表示變量組合的可行性
for k:=0 to meijucishu-1 do
begin
bins:=IntToBin(k);//將整型數轉化為二進制的字符串型表示
for j:= 1 to VarNum do
begin
x[j]:=StrToInt(copy(bins,32-VarNum+j,1));
//去二進制數的最后Varnum賦給變量X
StringGrid1.Cells[j,k+1]:=IntToStr(x[j]);
//同步顯示變量的取值
end;
temp:=True;
for i:=1 to ConNum do
begin
hangzhi:=0;
for j:=1 to VarNum do
hangzhi:=hangzhi+a[i,j]*x[j];
if (Sign(hangzhi-b[i])<>opt[i]) and (hangzhi<>b[i]) then
//此處巧妙的調用符號函數,并結合使用-1,0,1分別
//表示小于、等于、大于來比較變量組合是否滿足第i個約束條件
begin
temp:=False;
Break;//有一個不滿足,則跳出循環
end;
end;
if temp then
begin
biaoshi[k]:='+';//表示滿足所有約束條件的組合
end
else biaoshi[k]:='-';//不表示滿足所有約束條件的組合
for j:=1 to VarNum do
z[k]:=z[k]+x[j]*c[j]; //計算對應的目標函數值
end;
zuiyouzhi:=0;
for i:=0 to meijucishu-1 do
if leixing='Max' then//求最大化問題時,最優解的尋找
begin
if biaoshi[i]='+' then
if z[i]>zuiyouzhi then
begin
zuiyouzhi:=z[i];
end;
end
else//求最小化問題時,最優解的尋找
begin
if biaoshi[i]='+' then
if z[i]<zuiyouzhi then
begin
zuiyouzhi:=z[i];
end;
end;
//尋找最優值
n:=0;
for i:=0 to meijucishu-1 do
begin
if (abs(z[i]-zuiyouzhi)<0.000001) and (biaoshi[i]='+') then
begin //找多個最優解
biaoshi[i]:='*';
n:=n+1;
end;
StringGrid1.Cells[varNum+1,i+1]:=FloatToStr(z[i]);
StringGrid1.Cells[varNum+2,i+1]:=biaoshi[i];
end;
if n=0 then ShowMessage('該0-1規劃問題無可行整數解')
else showmessage('該0-1規劃問題共有'+inttostr(n)
+'個最優解'+#13+'如表中標有 * 的所示'+#13+'最優值是 '
+FormatFloat('0.#####',zuiyouzhi));
end;
{-----------程序的核心代碼,計算并顯示最優解和最優值------------}
procedure TForm2.BitBtn3Click(Sender: TObject);
begin
Form2.Close;
Form1.Close;//退出程序
end;
procedure TForm2.BitBtn2Click(Sender: TObject);
begin
Form1.Show; //返回到數據輸入窗口
end;
end.
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -