码迷,mamicode.com
首页 > 其他好文 > 详细

PAT甲级——A1029 Median

时间:2019-07-21 01:09:36      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:容器   ==   info   family   form   position   输入   int   pos   

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

标签:容器   ==   info   family   form   position   输入   int   pos   

原文地址:https://www.cnblogs.com/zzw1024/p/11219687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!