题目大意:
写程序读入一个整数序列。每次读入第奇数个数后,输出当前序列的中位数。
{以上感谢铎铎大牛提供的翻译}
我想出来的是离线算法:将整体读入之后快排,建立链表,首先求出最后一个中位数,然后按读入顺序从后向前每次删去两个数,有如下五种情况:
如果删去的两个数都比中位数大,那么将中位数的位置移到没有被删去的比当前中位数小的最大的数。
如果删去的两个数都比中位数小,那么将中位数的位置移到没有被删去的比当前中位数大的最小的数。
如果两个数中一个比中位数大而另一个比中位数小,那么当前中位数位置不动。
如果删去的是中位数和另一个比它大的数,那么中位数的位置移向没有被删去的比当前中位数小的最大的数。
如果删去的是中位数和另一个比它小的数,那么中位数的位置移向没有被删去的比当前中位数大的最小的数。
铎铎大牛的算法是维护两个堆,一个大根堆和一个小根堆。每次读入的时候将比当前中位数大的数加入小根堆,把比当前中位数小的数加入大根堆。依次输出即可。
CODE(双向链表)
Program Median;//By_tihspoet
Const
maxn=10001;
Var
i,k,m,n,p,move,t,o :Longint;
pre,next :Array[0..maxn]of Longint;
a,rank,rerank :Array[0..maxn]of Longint;
ans :Array[0..maxn]of Longint;
Procedure Qsort(l,r:Longint);
var i,j,k,temp:Longint;
begin
i:=l;j:=r;
k:=a[(i+j)>>1];
repeat
while a[i]<k do inc(i);
while a[j]>k do dec(j);
if i<=j then
begin
temp:=a[i];a[i]:=a[j];a[j]:=temp;
temp:=rank[i];rank[i]:=rank[j];rank[j]:=temp;
inc(i);dec(j);
end;
until i>j;
if i<r then Qsort(i,r);
if l<j then Qsort(l,j);
end;
Function Count(i:Longint):Longint;
begin
if rerank[i]<p then exit(-1) else exit(1);
end;
Procedure Delete_Table(i:Longint);
var p:Longint;
begin
p:=rerank[i];
pre[next[p]]:=pre[p];
next[pre[p]]:=next[p];
pre[p]:=0;next[p]:=0;
end;
Function Max(i,j:Longint):Longint;
begin
if i<j then exit(j);exit(i);
end;
BEGIN
readln(t);
for o:=1 to t do
begin
readln(m,n);
for i:=1 to n do
begin
read(a[i]);
rank[i]:=i;
end;
readln;
Qsort(1,n);
for i:=2 to n do pre[i]:=i-1;
for i:=1 to n-1 do next[i]:=i+1;
next[n]:=maxn;pre[maxn]:=n;
for i:=1 to n do rerank[rank[i]]:=i;
p:=(n+1)>>1;
ans[1]:=a[p];k:=1;
for i:=(n>>1) downto 1 do
begin
move:=0;
if (rerank[(i<<1)+1]=p) then
begin
inc(Move,Count(i<<1));
Delete_Table((i<<1));
if move>0 then
begin
p:=pre[p];
inc(k);ans[k]:=a[p];
end else
begin
p:=next[p];
inc(k);ans[k]:=a[p];
end;
Delete_Table((i<<1)+1);
end else if (rerank[i<<1]=p)then
begin
inc(Move,Count((i<<1)+1));
Delete_Table((i<<1)+1);
if Move>0 then
begin
p:=pre[p];
inc(k);ans[k]:=a[p];
end else
begin
p:=next[p];
inc(k);ans[k]:=a[p];
end;
Delete_Table(i<<1);
end else
begin
inc(Move,Count((i<<1)+1));
inc(Move,Count(i<<1));
Delete_Table((i<<1)+1);
Delete_Table((i<<1));
if move=0 then
begin
inc(k);
ans[k]:=a[p];
end else if move>0 then
begin
p:=pre[p];
inc(k);ans[k]:=a[p];
end else
begin
p:=next[p];
inc(k);ans[k]:=a[p];
end;
end;
end;
writeln(m,' ',(n>>1)+1);
while k>0 do
begin
for i:=k downto max(k-8,2) do write(ans[i],' ');
writeln(ans[Max(k-9,1)]);
dec(k,10);
end;
end;
END.