题目1004:Median
#include <stdio.h>
#include<algorithm>
using namespace std;
int a[2000100];
int main()
{
int n,m,i;
//freopen("G:\\in.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(i=n;i<m+n;i++)
scanf("%d",&a[i]);
sort(a,a+m+n);
printf("%d\n",a[(m+n-1)/2]); //注意啦:此处要减掉1,不然老报错。。。
}
return 0;
}
法2:merge两个有序表(优化)。
/**************************************************************
Problem: 1004
Language: C++
Result: Accepted
Time:0 ms
Memory:16644 kb
****************************************************************/
#include <stdio.h>
#include<algorithm>
using namespace std;
int a[1000010],b[1000010],c[2000010];
void merge(int t1[],int t2[],int n1,int n2)
{
int i=0,j=0,k=0;
while(i<n1&&j<n2){
if(t1[i]<=t2[j]){
c[k]=t1[i];
i++;k++;
}
else{
c[k]=t2[j];
j++;k++;
}
}
if(i==n1)
c[k++]=t2[j++];
if(j==n2)
c[k++]=t1[i++];
}
int main()
{
int n,m,i;
//freopen("G:\\in.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(i=0;i<m;i++)
scanf("%d",&b[i]);
merge(a,b,n,m);
printf("%d\n",c[(m+n-1)/2]);
}
return 0;
}