PTA_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

Sample Output:

13

題意:
給出兩個遞增數列,輸出它們無重複元素的中位數

分析:
用set最後一個測試點會超時,用數組存儲兩個序列,從頭比較,哪邊小則哪邊序號加一,直到一共選出了中位數個元素,有重複元素也不影響結果,因爲若位置不同則第一次出現必爲大第二次出現必爲小

代碼:

#include<cstdio>
#include<iostream>
using namespace std;

#define MAXN 200001
#define INF 0x7fffffff

int main()
{
	int N1, N2;
	long int S1[MAXN], S2[MAXN];
	ios::sync_with_stdio(false);
	cin>>N1;
	for(int i=0;i<N1;i++) cin>>S1[i];
	cin>>N2;
	for(int i=0;i<N2;i++) cin>>S2[i];
	S1[N1] = S2[N2] = INF;
	//一個序列已經結束但仍未到中位數時另一個序列中元素必小於此序列末尾,即相當於只在另一序列中遞進 
	int K = (N1+N2-1)/2, cnt1=0, cnt2=0, cnt=0;
	long int Media; 
	while(cnt++<K){
		if(S1[cnt1]<S2[cnt2]) cnt1++;
        else cnt2++;
	}
    Media = S1[cnt1]<S2[cnt2] ? S1[cnt1] : S2[cnt2];
    cout<<Media<<endl;
	return 0;	
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章