天天看點

pta--1029 Median(25 分)(思維&&解決記憶體超限)*

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
           

【分析】題意挺好了解的吧,就是輸出兩個序列合并後的中位數。注意兩個序列都是有序的。一開始直接用sort了,但是最後一個測試點說記憶體超限。然後把int都改成了long long,,,,然後,最後4個點都是記憶體超限。好吧,方法問題了~

思路及代碼參考大神:柳婼 の blog   https://www.liuchuo.net/archives/2248

分析:開一個數組,線上處理第二個數組。 第一二個數組(下标從1開始)分别有n,m個元素,中間數在(n + m + 1) / 2的位置。是以隻要從小到大數到(n + m + 1) / 2的位置就行了~ count計總個數 ,給第一個數組設定指針i,每次從第二個數組中讀入temp,檢查第一個數組中前幾個數是不是比temp小,小就count+1并判斷是否到數了中間數,到了就輸出。 如果數完比temp小的數還沒到中間數,count+1,檢查temp是不是中間數,是就輸出。循環上述過程。如果第二個數組讀取完了,還沒數到中間數,說明中間數在剩下的第一個數組中,就在剩下的數組中數到中間數位置即可

【代碼】

#include<iostream>
#include<cstdio>
using namespace std;
int k[200005];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&k[i]);
	int m;
	scanf("%d",&m);
	int temp,cnt=0,i=1;
	k[n+1]=0x7fffffff;//long int的最大值
	int midpos=(n+m+1)/2;
	for(int j=1;j<=m;j++)
	{
		scanf("%d",&temp);
		while(k[i]<temp)
		{
			cnt++;
			if(cnt==midpos)cout<<k[i];
			i++;
		}
		cnt++;
		if(cnt==midpos)cout<<temp;
	}
	while(i<=n)
	{
		cnt++;
		if(cnt==midpos)cout<<k[i];
		i++;
	}
	return 0;
}