您的位置:首页 > 其它

九度 1004 Median

2013-03-17 13:23 295 查看
题目1004:Median

时间限制:1 秒

内存限制:32 兆

特殊判题:否

提交:5803

解决:1586

题目描述:

Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences
is defined to be the median of the non-decreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.

Given two increasing sequences of integers, you are asked to find their median.

输入:

Each input file may contain more than one test case.

Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤1000000) is the size of that sequence. Then N integers follow, separated by a space.

It is guaranteed that all the integers are in the range of long int.

输出:

For each test case you should output the median of the two given sequences in a line.

样例输入:
4 11 12 13 14
5 9 10 15 16 17


样例输出:
13

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//const int SIZE=1000000;
int main()
{
//直接开1000000的数组程序停止工作 只好动态创建 或者声明为全局数组 不放在主函数内
//long int a[SIZE],b[SIZE];
int aNum,bNum,i,j,sum,index;
long int *a,*b,Median;
while(scanf("%d",&aNum)!=EOF)
{
a=(long int*)malloc(aNum*sizeof(long int));
for(i=0; i<aNum; i++)
scanf("%ld",&a[i]);

scanf("%d",&bNum);
b=(long int*)malloc(bNum*sizeof(long int));
for(i=0; i<bNum; i++)
scanf("%ld",&b[i]);

sum=aNum+bNum;
if(sum&1)//是奇数
index=(sum+1)/2;//向上取整
else
index=sum/2;
i=0,j=0;
int count=0;
Median=0;
while(count<index && i<aNum && j<bNum)
{
if(a[i]<=b[j])
{
Median=a[i];
i++;
}
else
{
Median=b[j];
j++;
}
count++;
}
//printf("%d %d",count,index);
while(count<index && i<aNum)
{
Median=a[i++];
count++;
}
while(count<index && j<bNum)
{
Median=b[j++];
count++;
}
printf("%ld\n",Median);
free(a);
free(b);
}
return 0;
}

/**************************************************************
Problem: 1004
User: windzhu
Language: C++
Result: Accepted
Time:10 ms
Memory:1012 kb
****************************************************************/


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