1029. Median

1029. Median (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 14
5 9 10 15 16 17
Sample Output
13
//int end这个变量导致编译错误 
#include<stdio.h>
#include<algorithm>
using namespace std;

long num1[1000002];
long num2[1000002];
long res[1000002];

bool cmp(long A, long B)
{
	return A < B;
}

int start, mid;
int End;
long* a;
long* b;
void median(int s1, int e1, int s2, int e2)
{
	int m1 = (s1+e1) / 2;
	int m2 = (s2+e2) / 2;
	if(s1 == e1)
	{
		mid = s1;
		start = s2;
		End = e2;
	}
	else if(a[m1] == b[m2])
	{
		mid = m1;
		start = m2;
		End = m2;
	}
	else if(a[m1] < b[m2])
		median(m1+1, e1, s2, e2-m1+s1-1);
	else if(a[m1] > b[m2])
		median(s1, m1, s2+e1-m1, e2);
}

int main()
{
	int n1, n2, i;
	while(scanf("%d", &n1) != EOF)
	{
		for(i = 0; i < n1; i ++)
			scanf("%ld", &num1[i]);
		
		scanf("%d", &n2);
		for(i = 0; i < n2; i ++)
			scanf("%ld", &num2[i]);
		int min, max;
		if(n1 <= n2)
		{
			a = num1;
			b = num2;
			min = n1;
			max = n2;
		}
		else
		{
			a = num2;
			b = num1;
			min = n2;
			max = n1;
		}
		
		median(0, min-1, 0, max-1);
		for(i = 0; i < End-start+1; i ++)
			res[i] = b[start+i];
		res[i] = a[mid];
		
		sort(res, res+i+1, cmp);
		printf("%ld\n", res[i/2]);
	}
	return 0;
}


你可能感兴趣的:(1029. Median)