主持人舒冬:我的程序结果没错,为什么不行?帮忙改一下吧!

来源:百度文库 编辑:高校问答 时间:2024/04/29 20:19:17
Problem
你有一堆石头质量分别为W1,W2,W3...WN.(W<=100000)现在需要你将石头合并为两堆,使两堆质量的差为最小。

Input
该程序有多组测试数据,每组测试数据第一行为整数N(1<=N<=20),表示有N堆石子。接下去N行,为每堆石子的质量。

我的程序:
program tug;
var n,i,j,k,x,y:integer;
a:array[1..450] of integer;
begin
readln(n);
for i:=1 to n do
readln(a[i]);
for i:=1 to n-1 do
for j:=i+1 to n do
if a[i]>a[j] then
begin
k:=a[i];
a[i]:=a[j];
a[j]:=k;
end;
x:=0;
y:=0;
for i:=1 to n div 2 do
if x>y then
begin
x:=x+a[i];
y:=y+a[n-i+1];
end
else
begin
x:=x+a[n-i+1];
y:=y+a[i];
end;
if odd(n) then
if x<y then x:=x+a[n div 2+1]
else y:=y+a[n div 2+1];
if x<y then writeln(y-x)
else writeln(x-y);
end.

Output
每组测试数据只需输出合并后两堆的质量差的最小值。

Sample Input
5
5
8
13
27
14
2
4
4

Sample Output
3
0
还有一条程序(内存占太大),也改一下吧:
program dd;
var a:array [1..100] of integer;
b:array [0..100,0..50000] of boolean;
m,n,num,total,max,i,j,k:longint;
begin
total:=maxlongint;
fillchar(b,sizeof(b),#0);
b[0,0]:=true;
readln(n);
for i:=1 to n do
begin
readln(a[i]);
num:=num+a[i];
end;
m:=(n+1) div 2;
for i:=1 to n do
for j:=m-1 downto 0 do
for k:=450*i downto 0 do
if b[j,k] then b[j+1,k+a[i]]:=true;
for i:=450*m downto 1 do
if (b[m,i])and (abs(num-2*i)<total) then
begin
total:=abs(num-2*i);
if num-2*i>0 then max:=i else max:=num-i;
end;
writeln(num-max-max);
end.