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是为了判断时方便,不用再判断队列是否为空,最大数肯定不会被弹出。

    ---------------- 坚持每天学习一点点
  • 相关阅读:
    从零开始学架构(三)UML建模
    【网址收藏】博客园主题美化
    完美解决国内访问GitHub速度太慢的难题
    SpringBoot+slf4j线程池全链路调用日志跟踪 二
    SpringBoot+slf4j实现全链路调用日志跟踪 一
    2021年java最全面试宝典【核心知识整理】
    [中级]系统集成项目管理工程师历年真题及参考答案
    线程池ThreadPoolExecutor最全实战案例
    大厂git分支管理规范:gitflow规范指南
    IdentityServer4
  • 原文地址:https://www.cnblogs.com/tccbj/p/10397973.html
Copyright © 2011-2022 走看看