Typesetting math: 100%

1029. 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

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 (<=1000000) 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

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

本题是本意是考察归并排序, 两路归并, 但是由于题目的数据量比较大(N10N10) 因此如果直接开两个long数组

int a[1000000], b[1000000]

会开崩掉, 接下来需要解决数据量大的问题, 一种办法是在全局区域定义a, b这样可以防止数组开崩掉,但是具体的没有试过, 这题用了一个比较奇怪的方法, 使用vector先装好一个数组,然后一边读取一边归并,这样可以省一个中间数组,虽然这样做的, 结果速度还行,但是内存占用很多,不知道为什么,有机会研究一下, Mark

#include <iostream>
#include <vector>
using namespace std;

void merge(vector<long> a, vector<long> & res)
{
    int N;
    cin >> N;
    int i = 0;
    while(N--)
    {
        long num;
        cin >> num;
        if(a[i] < num)
        {
            while(a[i] < num && i != a.size()) //一边读取一边归并
            {
                res.push_back(a[i]);
                i++;
            }
            res.push_back(num);
            if(i == a.size())
            {
                break;
            }
        }
        else
        {
            res.push_back(num);
        }
    }

    if(i == a.size())
    {
        while(N--)
        {
            long num;
            cin >> num;
            res.push_back(num);
        }
    }
    else{
        while( i != a.size())
        {
            res.push_back(a[i]);
            i++;
        }
    }
}

int main()
{
    vector<long> a;
    int N;
    cin >> N;
    int n = N;
    while(n--)
    {
        long num;
        cin >> num;
        a.push_back(num);
    }

    vector<long> res;
    merge(a, res);
    cout << res[(res.size() - 1) / 2] << endl;
    return 0;
}

posted on   Prince1994  阅读(136)  评论(0编辑  收藏  举报

编辑推荐:
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
阅读排行:
· 短信接口被刷爆:我用Nginx临时止血
· 面试官:如果某个业务量突然提升100倍QPS你会怎么做?
· .NET 平台上的开源模型训练与推理进展
· 聊聊智商税:AI知识库
· Google发布A2A开源协议:“MCP+A2A”成未来标配?
点击右上角即可分享
微信分享提示