1. 程式人生 > 其它 >【19行程式碼AC,簡潔】1029 Median (25 分)

【19行程式碼AC,簡潔】1029 Median (25 分)

技術標籤:PAT甲級佇列PATPAT甲級

立志用最少的程式碼做最高效的表達


PAT甲級最優題解——>傳送門


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


題意: 分兩行輸入兩個序列, 每行第一個數n為序列個數。 將兩個序列求並集,非降序排序,求中位數。 如果序列數為偶數,則輸出左側的數。

分析:
解法一:定義優先佇列,將兩個序列數入隊,輸出中位數。
解法二:定義multiset(有序不去重集合),輸入,輸出中位數。

注意:
如果採用cin、cout輸入輸出,需要取消流同步,即:ios::sync_with_stdio(false);。 速度相較於scanf、printf來說更快。


儲備知識擴充套件(很重要,提高效率,降低碼量):

  • set——有序去重集合。

  • map——有序去重對映

  • multiset——有序不去重集合

  • multimap——有序不去重對映

  • unordered_set——無序不去重集合(普通集合)

  • unordered_map——無序不去重對映(普通對映)


解法一:優先佇列

#include<bits/stdc++.h>
using namespace std;
using gg = long long;
int main() {
	ios::sync_with_stdio(false);
	//升序優先佇列(越大則優先順序越高) 
	priority_queue<gg, vector<gg>, greater<gg> >q;
	gg len = 0;			//集合長度 
	for(gg i = 0; i < 2; i++) {
		gg n; cin >> n; 
		len += n;
		while(n--) {
			gg x; cin >> x; q.push(x); 
		} 
	} 
	int last = (len+1)/2-1;
	for(int i = 0; i < last; i++) q.pop();
	cout << q.top();
	return 0;
}

耗時:


解法二:multiset集合

#include<bits/stdc++.h>
using namespace std;
using gg = long long;
int main() {
	ios::sync_with_stdio(false);
	multiset<gg>m;
	gg len = 0;
	for(gg i = 0; i < 2; i++) {
		gg n; cin >> n; 
		len += n;
		while(n--) {
			gg x; cin >> x; m.insert(x);  
		} 
	} 
	gg i = 0, last = (len+1)/2-1;
	for(auto um : m) 
		if(i++ == last) { cout << um; break; }
	
	return 0;
}

耗時(比起優先佇列高了一些,因為集合每次插入元素的複雜度都為O(nlogn)):


痛苦難道是白忍受的嗎?他應該使我們偉大!      ——托馬斯·曼