zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    A
    单调栈详解
    C
    序列自动机
    codeforces 805 E. Ice cream coloring(dfs)
    codeforces 805 D. Minimum number of steps(数学)
    codeforces 572 D. Minimization(dp+ 思维)
    codeforces 572 C. Lengthening Sticks(数学)
    codeforces 284 E. Coin Troubles(背包+思维)
    codeforces 284 D. Cow Program(记忆化搜索)
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11219687.html
Copyright © 2011-2022 走看看