PAT A1029:Median之sort排序

题目描述

PAT A1029
1029 Median (25分)
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 Specification:
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 (≤2×10^5 ) 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 Specification:
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

求解思路

一开始使用的是multiset,只能使用迭代器访问,所以使用了一个变量控制,到达了中位即输出。但由于数据量可能过大,导致了运行超时,所以使用sort排序后直接用下标访问。

实现代码(AC)
#includecstdio
#includeiostream
#includevector
#includealgorithm
using namespace std;
int main()
{
	int n,m;
	scanf("%d",n);
	int a[n];
	//multisetints;
	vectorints;
	for(int i=0;in;i++)
	{
		scanf("%d",a[i]);
		s.push_back(a[i]);
	}	
	scanf("%d",m);
	int b[m];
	for(int i=0;im;i++)
	{
		scanf("%d",b[i]);
		s.push_back(b[i]);
	}
	sort(s.begin(),s.end()); 
	printf("%d\n",s[(n+m-1)/2]);
	return 0;
}

代码(最后一组数据运行超时)

#includecstdio
#includeiostream
#includeset
using namespace std;
int main()
{
	int n,m;
	scanf("%d",n);
	int a[n];
	multisetints;
	for(int i=0;in;i++)
	{
		scanf("%d",a[i]);
		s.insert(a[i]);
	}	
	scanf("%d",m);
	int b[m];
	for(int i=0;im;i++)
	{
		scanf("%d",b[i]);
		s.insert(b[i]);
	}
	int count=0;
	for(multisetint::iterator it=s.begin();it!=s.end();it++,count++)
	{
		if(count==(n+m-1)/2)	printf("%d\n",*it);
	}
	return 0;
}
最新回复(0)
/jishu4BWmC9Vz14_2BredsiW4jvF6rm9h_2BxE2javcPCnA_3D_3D4794624
8 简首页