- 最小差距
- 2016-08-02 15:51:48 @
大神求救……代码如下(带注释):
program zz;
var a,s:array[1..10] of shortint;
var y:array[0..9] of shortint;
var b,c,d,e,m,n,o,p,q,r,t,u,v,w,x,z,f:longint;
begin
readln(b);
for c:=1 to b do
begin
fillchar(a,sizeof(a),0);//初始化
fillchar(y,sizeof(y),0);
f:=0;
readln(d);
for e:=1 to d do //基数排序
begin
read(z);
y[z]:=y[z]+1;
end;
for e:=0 to 9 do
while y[e]>0 do
begin
f:=f+1;
a[f]:=e;
y[e]:=y[e]-1;
end;
readln;
if f mod 2=1 then begin //是奇数
o:=f;
if a[1]=0 then begin //判断首位是0
p:=a[1];
a[1]:=a[2];
a[2]:=p;
end;
m:=a[1];
for q:=2 to f div 2+1 do //取数
begin
m:=m*10+a[q];
n:=n*10+a[o];
o:=o-1;
end;
writeln(abs(m-n));
end
else begin //偶数
t:=1000000000; //初始化
for r:=1 to f-1 do
begin
s:=a;//初始化
if s[r]=0 then begin //判断首位是0的情况
p:=s[r];
s[r]:=s[r+1];
s[r+1]:=p;
end;
if s[r+1]=0 then begin
p:=s[r+1];
s[r+1]:=s[r+2];
s[r+2]:=p;
end;
v:=f;
w:=f div 2;
m:=s[r];
n:=s[r+1];
s[r]:=-1; //用过的置-1
s[r+1]:=-1;
u:=1;
while u<=w-1 do //取k(n=2k)-1 位
begin
if s[v]<>-1 then begin
u:=u+1;
m:=m*10+s[v];
s[v]:=-1;
end;
v:=v-1;
end;
u:=1;
v:=1;
while u<=w-1 do
begin
if s[v]<>-1 then begin
u:=u+1;
n:=n*10+s[v];
s[v]:=-1;
end;
v:=v+1;
end;
if abs(m-n)<t then t:=abs(m-n);//更新答案
end;
if t<>1000000000 then writeln(t)
else writeln('0');
end;
end;
end.
1 条评论
-
刘卓逸 LV 8 @ 2016-08-14 19:17:51
这题特别坑,你要处理有相同的数出现时的情况
- 1