POJ3784Running Median——双向链表/堆

来源:互联网 发布:linux iso文件怎么挂载 编辑:程序博客网 时间:2024/06/05 07:44
 

题目大意:

写程序读入一个整数序列。每次读入第奇数个数后,输出当前序列的中位数。

 

{以上感谢铎铎大牛提供的翻译}

 

我想出来的是离线算法:将整体读入之后快排,建立链表,首先求出最后一个中位数,然后按读入顺序从后向前每次删去两个数,有如下五种情况:

如果删去的两个数都比中位数大,那么将中位数的位置移到没有被删去的比当前中位数小的最大的数。

如果删去的两个数都比中位数小,那么将中位数的位置移到没有被删去的比当前中位数大的最小的数。

如果两个数中一个比中位数大而另一个比中位数小,那么当前中位数位置不动。

如果删去的是中位数和另一个比它大的数,那么中位数的位置移向没有被删去的比当前中位数小的最大的数。

如果删去的是中位数和另一个比它小的数,那么中位数的位置移向没有被删去的比当前中位数大的最小的数。

 

 

铎铎大牛的算法是维护两个堆,一个大根堆和一个小根堆。每次读入的时候将比当前中位数大的数加入小根堆,把比当前中位数小的数加入大根堆。依次输出即可。

 

CODE(双向链表)

Program Median;//By_tihspoetConstmaxn=10001;Vari,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;begini:=l;j:=r;k:=a[(i+j)>>1];repeatwhile a[i]<k do inc(i);while a[j]>k do dec(j);if i<=j thenbegintemp:=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;beginif rerank[i]<p then exit(-1) else exit(1);end;Procedure Delete_Table(i:Longint);var p:Longint;beginp:=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;beginif i<j then exit(j);exit(i);end;BEGINreadln(t);for o:=1 to t dobeginreadln(m,n);for i:=1 to n dobeginread(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 dobeginmove:=0;if (rerank[(i<<1)+1]=p) thenbegininc(Move,Count(i<<1));Delete_Table((i<<1));if move>0 thenbeginp:=pre[p];inc(k);ans[k]:=a[p];end elsebeginp:=next[p];inc(k);ans[k]:=a[p];end;Delete_Table((i<<1)+1);end else if (rerank[i<<1]=p)thenbegininc(Move,Count((i<<1)+1));Delete_Table((i<<1)+1);if Move>0 thenbeginp:=pre[p];inc(k);ans[k]:=a[p];end elsebeginp:=next[p];inc(k);ans[k]:=a[p];end;Delete_Table(i<<1);end elsebegininc(Move,Count((i<<1)+1));inc(Move,Count(i<<1));Delete_Table((i<<1)+1);Delete_Table((i<<1));if move=0 thenbegininc(k);ans[k]:=a[p];end else if move>0 thenbeginp:=pre[p];inc(k);ans[k]:=a[p];end elsebeginp:=next[p];inc(k);ans[k]:=a[p];end;end;end;writeln(m,' ',(n>>1)+1);while k>0 do beginfor i:=k downto max(k-8,2) do write(ans[i],' ');writeln(ans[Max(k-9,1)]);dec(k,10);end;end;END.


 

原创粉丝点击