PAT甲级——A1029 Median

Posted zzw1024

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT甲级——A1029 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 (≤) 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

这道题,我要说道说道;
这道题和考究内存的使用,如果你的代码会去保存输入的两组数据,我相信,测试会提示“超内存”的错误;
所以,就保存一组数据,与另一组数据进行比较就行,不用保存;
一般简单的int数组远比任何容器都省内存!!!
 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 
 5     int res[200005], m, n, i, j, a, index = 0;
 6     cin >> m;
 7     for (i = 1; i <= m; ++i)
 8         cin >> res[i];
 9     cin >> n;
10     for (i = 1,j=1; i <= n; ++i)
11     
12         cin >> a;
13         while (j <= m && a > res[j])
14         
15             ++index;
16             if (index == (m + n + 1) / 2)
17             
18                 cout << res[j] << endl;
19                 return 0;
20             
21             ++j;
22         
23         ++index;
24         if (index == (m + n + 1) / 2)
25         
26             cout << a << endl;
27             return 0;
28         
29     
30     while(j <= m)
31     
32         ++index;
33         if (index == (m + n + 1) / 2)
34         
35             cout << res[j] << endl;
36             return 0;
37         
38         ++j;
39     
40     return 0;
41 

 

以上是关于PAT甲级——A1029 Median的主要内容,如果未能解决你的问题,请参考以下文章

pat甲级没做出来没有分吗

pat甲级60分啥水平

pat可以直接考甲级吗

PAT甲级考前整理

pat甲级考试+pat1051+1056

菜鸟记录PAT甲级1003--Emergency