PAT-A 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

程序代码:

#include<stdio.h>
#define MAX 1000000
long a[MAX];
long b[MAX];
int main()
{
    long long m,n,i;
    scanf("%lld",&m);
    for(i=0;i<m;i++)
        scanf("%lld",&a[i]);
    scanf("%lld",&n);
    for(i=0;i<n;i++)
        scanf("%lld",&b[i]);
    long long sum = (m+n+1)/2,count = 0;
    long *p=&a[0],*q=&b[0],*s;
    while(p<=&a[m-1]&&q<=&b[n-1])
    {
        if(*p<*q)
        {
            count++;
            s=p;
            p++;
        }
        else
        {
            count++;
            s=q;
            q++;
        }
        if(count==sum)
        {
            printf("%ld",*s);
            return 0;
        }

    }
    if(count<sum)
    {
        while(p<=&a[m-1])
        {
            count++;
            s=p;
            p++;
            if(count == sum)
            {
                printf("%ld",*s);
                return 0;
            }
        }
        while(q<=&b[n-1])
        {
            count++;
            s=q;
            q++;    
            if(count==sum)
            {
                printf("%ld",*s);
                return 0;
            }
        }
    }
    return 1;
}
全部评论

相关推荐

服从性笔试吗,发这么多笔,现在还在发。
蟑螂恶霸zZ:傻 x 公司,发两次笔试,两次部门匹配挂,
投递金山WPS等公司10个岗位 >
点赞 评论 收藏
分享
11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务