PAT 1029 Median

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×105​​) 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
 注意点:因为测试点的输入数据可能非常大, 所以一定要用scanf, 否则会超时
 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 int main(){
 5   int n, i, m;
 6   cin>>n;
 7   vector<int> v(n+1);
 8   for(i=0; i<n; i++) scanf("%d", &v[i]);
 9   cin>>m;
10   int cnt=0, idx=0, ans, mid=(m+n+1)/2;
11   for(i=0; i<m; i++){
12     int num;
13     scanf("%d", &num);
14     while(idx<n&&v[idx]<num){
15       cnt++;
16       if(cnt==mid) cout<<v[idx]<<endl;
17       idx++;
18     }
19     cnt++;
20     if(cnt==mid) cout<<num<<endl;
21   }
22   while(idx<n){
23     cnt++;
24     if(cnt==mid)  cout<<v[idx]<<endl;
25     idx++;
26   }
27   return 0;
28 }

 

 
 
posted @ 2018-09-02 11:15  赖兴宇  阅读(340)  评论(0编辑  收藏  举报