【PAT】【Advanced Level】1029. Median (25)

来源:互联网 发布:二级域名解析系统源码 编辑:程序博客网 时间:2024/06/04 00:59

1029. Median (25)

时间限制
1000 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 145 9 10 15 16 17
Sample Output
13
原题链接:

https://www.patest.cn/contests/pat-a-practise/1029

思路:

二路归并

坑点:

数目为偶数,下标取下界。

归并时,注意其中之一超范围的情况

CODE:

#include<iostream>#include<cstdio>#include<algorithm>using namespace std;long long a[1000001];long long b[1000001];int main(){    long n1;    cin>>n1;    for (long i=0;i<n1;i++)        scanf("%lld",&a[i]);    long n2;    cin>>n2;    for (long i=0;i<n2;i++)        scanf("%lld",&b[i]);    long num=0;    long s1=0;    long s2=0;    long re=0;    long re1=0;    while(1)    {        if (s2<n2 && a[s1]>b[s2])        {            re=re1;            re1=b[s2];            num++;            if (num ==((n1+n2)/2+1)) break;            s2++;        }        else if (s1<n1 && a[s1]<=b[s2])        {            re=re1;            re1=a[s1];            num++;            if (num ==((n1+n2)/2+1)) break;            s1++;        }        else if (s1>=n1)        {            re=re1;            re1=b[s2];            num++;            if (num ==((n1+n2)/2+1)) break;            s2++;        }        else if (s2>=n2)        {            re=re1;            re1=a[s1];            num++;            if (num ==((n1+n2)/2+1)) break;            s1++;        }    }    if ((n1+n2)%2==0) cout<<re;    else        cout<<re1;    return 0;}




原创粉丝点击