PAT 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

题目大意:找出两个数列中的中位数。每一行的第一个数字表示该数列的 个数。

坑点:如果开辟两个数列分别存储这两个数,由于数列范围很大,所以会运行超时。

          如果不用vector定义数组,那么要将数组定义在任何函数的外面,不然会爆栈。

          因为输入量较大100000,所以不能用c++的输入输出流函数  cin  cout  而要用scanf();

思想:1.两个数列都为升序排列,所以可类比归并排序的思想,将一个数组,在逻辑上合并到另一个数组里(不是真的合并,只是借用思想)。

          2.因为已经告诉两个数列的个数,所以很方便的求得中位数在合并后的数列中所在位置。

          3.我们可以将数列1存入数组中,然后在线输入第二个数列,输入一个比较一次,然后用一个计数变量记录比较的个数,当变量等于中位数位置时,则找出了中位数。

#include<iostream>
#include<vector>
using namespace std;
 int number1[200001];
int main() {
	long int n, m;
	scanf("%d", &n);
	//输入第一个数列
	for (int i = 1; i <= n; i++) {
		scanf("%d",&number1[i]);
	}
	scanf("%d", &m);
	int midel = 0;
	midel = (n + m + 1) / 2;
	int count=0,num,ptr=1;;
	for(int i=0;i<m;i++){
		scanf("%d",&num);
		//当第一个数列元素的值小于第二个数列输入的值
		while(ptr<=n&&number1[ptr]<num){
			//记住要先将计数器加一,将现在所指的元素考虑进去。
			count++;
			if(count==midel)cout<<number1[ptr]<<endl;
			ptr++;
		}
			count++;
			if(count==midel) cout<<num<<endl;
	}
	//当第二个元素全部输入都没有到达中位数位置,说明中位数在第一个数列中
	while(ptr<=n){
		count++;
		if(count==midel)cout<<number1[ptr]<<endl;
		ptr++;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值