zoukankan      html  css  js  c++  java
  • PAT A1029 Median (25 分)——队列

    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
    
     
    #include <stdio.h>
    #include <stdlib.h>
    #include <algorithm>
    #include <queue>
    #include <limits.h>
    using namespace std;
    queue<int> a,b;
    
    int main() {
        int n,m;
        int x;
        scanf("%d", &n);
        int count=0;
        for (int j = 0; j < n; j++) {
            scanf("%d", &x);
            a.push(x);
        }
        a.push(INT_MAX);
        scanf("%d", &m);
        int point = (n + m - 1) / 2;
        for (int i = 0; i < m; i++) {
            int temp;
            scanf("%d", &temp);
            b.push(temp);
            if (count == point) {
                printf("%d", min(a.front(), b.front()));
                return 0;
            }
            if (a.front() < temp) {
                a.pop();
            }
            else {
                b.pop();
            }
            
            count++;
        }
        b.push(INT_MAX);
        while (count != point) {
            if (a.front() < b.front()) {
                a.pop();
            }
            else {
                b.pop();
            }
            count++;
        }
        printf("%d", min(a.front(), b.front()));
    }

    注意点:这道题内存限制1.5M,全部储存起来做内存就超了,而题目里说给的数字不超过long int,实际测试发现没有超过int。

    要不超过内存,必须使用边读数据边处理的方法,中间数就是要把前面 (n+m-1)/2 个数弹出,用队列实现,只要读第二个数组时一个个判断就好了。

    ps:加入一个INT_MAX是为了判断时方便,不用再判断队列是否为空,最大数肯定不会被弹出。

    ---------------- 坚持每天学习一点点
  • 相关阅读:
    UIApplication sharedApplication详细解释-IOS
    CocoaPods版本升级
    iOS更改状态栏颜色__
    代码实现UIPickerView
    在UINavigation上添加UISearchBar
    runtime实际应用---
    runtime实际应用
    runtime 运行时机制 完全解读(二)
    RunTime机制--原理(一)
    同步推笔试坑录
  • 原文地址:https://www.cnblogs.com/tccbj/p/10397973.html
Copyright © 2011-2022 走看看