讨论 / 单调队列 o(n)
woshimishuo 2011-12-28 01:28:00
点我顶贴 收藏 删除
var a,b:array[0..11000] of longint;

i,j,n,temp,h1,h2,t1,t2,ans,t:longint;

procedure qsort(x,y:longint);

var i,j,mid:longint;

begin

i:=x;j:=y;mid:=a[(x+y)>>1];

while i<=j do

begin

while a[i]<mid do inc(i);

while a[j]>mid do dec(j);

if i<=j then

begin

t:=a[i];

a[i]:=a[j];

a[j]:=t;

inc(i);dec(j);

end;

end;

if i<y then qsort(i,y);

if x<j then qsort(x,j);

end;

function min(a,b,c:longint):longint;

begin

if (a<b) and (a<c) then exit(a);

if (b<a) and (b<c) then exit(b);

exit(c);

end;

begin

readln(n);

for i:=1 to n do

read(a[i]);

qsort(1,n);

for i:=1 to n do

b[i]:=maxlongint>>1;

h1:=1;h2:=1;t2:=0;

a[n+1]:=maxlongint>>1;a[n+2]:=maxlongint>>1;

for i:=1 to n-1 do

begin

temp:=min(a[h1]+a[h1+1],b[h2]+b[h2+1],a[h1]+b[h2]);

if temp=a[h1]+a[h1+1] then inc(h1,2) else

if temp=b[h2]+b[h2+1] then inc(h2,2)

else if temp=a[h1]+b[h2] then begin inc(h1);inc(h2);end;

inc(t2);

b[t2]:=temp;

ans:=ans+temp;

end;

writeln(ans);

end.

查看更多回复
提交回复