1029. Median (25)

来源:互联网 发布:黄岛java开发招聘信息 编辑:程序博客网 时间:2024/04/29 20:51

题目要求

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 nondecreasing 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.

Input

Each input file contains 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.

Output

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

Sample Input
4 11 12 13 145 9 10 15 16 17
Sample Output
13
分析:

这一题就是一个二路归并的实现,输入给的每一个序列都是有序的,连预排序都省了。没什么可说的,用严书的数据结构上的2路归并算法可以轻松实现。要注意的就是只是找中值,而不是归并排序。

在存储的时候,两个有序表可能已经很大了,我的机器上个long是8B(ubuntu 14.04)。如果都是1,000,000大小的话,一个有序表就8MB大小了,如果为了存储2路归并的结果的话,一共需要24MB,这个应该会在测试的时候内存超过界限(我没试过)。所以只需要用一个long变量记录下每一次归并的结果,如果这个值是第median个值的话就打印。


代码如下:

#include <stdio.h>#include <stdlib.h>#define PRINT_I(x) printf("%s = %d\n",#x,x);#define PRINT_F(x) printf("%s = %f\n",#x,x);#define PRINT_S(x) printf("%s = %s\n",#x,x);int main(int argc,char* argv[]){int i,j,n1,n2,index,median;long *s1,*s2,median_value;//freopen("input","r",stdin);scanf("%d",&n1);s1 = (long *)malloc(sizeof(long)*n1);for(i=0;i<n1;++i)scanf("%ld",&s1[i]);scanf("%d",&n2);s2 = (long *)malloc(sizeof(long)*n2);for(i=0;i<n2;++i)scanf("%ld",&s2[i]);//2-mergei = j = index = 0;median = (n1+n2-1) / 2;while(i<n1&&j<n2){median_value = (s1[i] < s2[j]) ? s1[i++] : s2[j++];if(index++ == median){printf("%ld\n",median_value);return 0;}}while(i<n1){median_value = s1[i++];if(index++ == median){printf("%ld\n",median_value);return 0;}}while(j<n2){median_value = s2[j++];if(index++ == median){printf("%ld\n",median_value);return 0;}}free(s2);free(s1);return 0;}


0 0