首页 > 其他 > 详细

PAT 1029 Median (合并有序序列)

时间:2020-03-08 23:29:32      阅读:75      评论:0      收藏:0      [点我收藏+]

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.

思路

合并有序的序列

代码

#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <queue>
#include <stack>
#include <functional>
#include <limits.h> 
using namespace std;

long long a1[200000 + 10];
long long a2[200000 + 10];
long long ans[500000 + 10];
int main() {
    int N, M;
    scanf("%d", &N);
    for(int i = 0; i < N; i++)      scanf("%lld", a1 + i);
    scanf("%d", &M);
    for(int i = 0; i < M; i++)      scanf("%lld", a2 + i);
    int pos = 0;
    int i = 0, j = 0;
    while(i < N || j < M){
        if(pos > N + M / 2) break;
        if(i < N && j < M)  ans[pos++] = a1[i] < a2[j] ? a1[i++] : a2[j++];
        else if (i < N)     ans[pos++] = a1[i++];           
        else                ans[pos++] = a2[j++];
    }
    if((N + M) % 2 == 0)    cout << ans[(N + M) / 2 - 1] << endl;
    else                    cout << ans[(N + M) >> 1] << endl;
    return 0; 
}

PAT 1029 Median (合并有序序列)

原文:https://www.cnblogs.com/woxiaosade/p/12445690.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!