思路:首先将x数组排序,然后二分枚举答案mid,二分查找x【i】+mid在原数组的位置,检验数量是否在范围内,调整即可。
程序(有点小问题,还请大牛们查下错):
var
n,i,l,r,cn2,k,mid:longint;
a:array[0..110000]of longint;
function lower(left,right,xx:longint):longint;
var
mid:longint;
begin
while left<right do
begin
mid:=(left+right)shr 1;
if a[mid]<xx then left:=mid+1
else right:=mid;
end;
exit(left);
end;
function check(mid:longint):boolean;
var
cnt,i:longint;
begin
cnt:=0;
for i:=1 to n-1 do
cnt:=cnt+n-lower(i+1,n,mid+a[i]);
exit(cnt<=cn2 shr 1);
end;
procedure qsort(l,r:longint);
var
i,j,x,t:longint;
begin
i:=l;j:=r;x:=a[(l+r)shr 1];
repeat
while a[i]<x do i:=i+1;
while a[j]>x do j:=j-1;
if i<=j then
begin
t:=a[i];a[i]:=a[j];a[j]:=t;
i:=i+1;j:=j-1;
end;
until i>j;
if i<r then qsort(i,r);
if J>l then qsort(l,j);
end;
begin
while not eof do
begin
readln(n);
l:=maxlongint;
fillchar(a,sizeof(a),0);
for i:=1 to n do
read(a[i]);
qsort(1,n);
cn2:=n*(N-1)shr 1;
r:=a[n]-a[1]+1;l:=0;
while l+1<r do
begin
mid:=(l+r)shr 1;
if check(mid) then r:=mid
else l:=mid;
end;
writeln(l);
end;
end.