您的位置:首页 > 其它

1029. Median (25)

2014-01-28 13:30 483 查看
GivenanincreasingsequenceSofNintegers,themedianisthenumberatthemiddleposition.Forexample,themedianofS1={11,12,13,14}is12,andthemedianofS2={9,10,15,16,17}is15.Themedianoftwosequencesisdefinedtobethe
medianofthenondecreasingsequencewhichcontainsalltheelementsofbothsequences.Forexample,themedianofS1andS2is13.

Giventwoincreasingsequencesofintegers,youareaskedtofindtheirmedian.

Input

Eachinputfilecontainsonetestcase.Eachcaseoccupies2lines,eachgivestheinformationofasequence.Foreachsequence,thefirstpositiveintegerN(<=1000000)isthesizeofthatsequence.ThenNintegersfollow,separatedbyaspace.Itis
guaranteedthatalltheintegersareintherangeoflongint.

Output

Foreachtestcaseyoushouldoutputthemedianofthetwogivensequencesinaline.

SampleInput
411121314
5910151617

SampleOutput
13

注意点:因为给出的数据很有特点(已经有序),用快速排序的话时间复杂度为O(NlogN)还是有两个测试点通不过,通过可并排序的方法的时间复杂度为O(N+M)可以AC,注意不要用C++的流来完成数据的输入,会有很多测试点超时,要用stdio.h库的scanf()和printf()来完成

参考代码:


#include<iostream>
#include<stdio.h>
usingnamespacestd;
intmain()
{
intM,N;
scanf("%d",&M);
int*arr1=newint[M];
for(inti=0;i<M;i++){
scanf("%d",arr1+i);
}
scanf("%d",&N);
int*arr2=newint
;
for(inti=0;i<N;i++){
scanf("%d",arr2+i);
}
intK=M+N;
int*arr3=newint[K];
intstart=0,p1=0,p2=0;
while(p1!=M||p2!=N){
if(p1==M){
arr3[start++]=arr2[p2++];
continue;
}
if(p2==N){
arr3[start++]=arr1[p1++];
continue;
}
if(arr1[p1]<arr2[p2]){
arr3[start++]=arr1[p1++];
}else{
arr3[start++]=arr2[p2++];
}
}
if(K%2==0)
printf("%d",arr3[K/2-1]);
else
printf("%d",arr3[K/2]);
return0;
}

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: