PAT 1029 Median

1029 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<iostream>
#include <algorithm>
#include<string.h>
#include<queue>
using namespace std;

int main() {
    priority_queue<long int> pq;
    int m,n;
    scanf("%d",&m);
    long int t;
    for(int i=0;i<m;i++){
        scanf("%ld",&t);
        pq.push(t);
    }
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%ld",&t);
        pq.push(t);
    }
    int x=(m+n)/2;
    for(int i=0;i<x;i++){
        pq.pop();
    }
    printf("%ld",pq.top());
    return 0;
}

//这个代码是取巧用了优先队列,利用它的堆排序的性质,先入队,然后再出队,出到顶端是中位数的情况,在牛客网上通过,但是在pat上有最后4个 测试点是内存超限,那应该就是不行了,不能用优先队列来实现。但是不用的话,我一时想不起来该怎么做。

猜你喜欢

转载自www.cnblogs.com/BlueBlueSea/p/9446101.html