PAT_1029: Median

来源:互联网 发布:王奔宏的淘宝店 编辑:程序博客网 时间:2024/04/26 00:36

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
备注: 两个数组各设一个指针,比较当前数大小,小的那个指针向前走一步,同时判断是否为中位数,注意不能数组越界。
#include<stdio.h>int main(){int n1,n2,middle;long int *a,*b;scanf("%d",&n1);a = new long[n1];for(int i=0;i<n1;i++)scanf("%ld",&a[i]);scanf("%d",&n2);b = new long[n2];for(int i=0;i<n2;i++)scanf("%ld",&b[i]);if((n1+n2)%2==0)middle = (n1+n2)/2;elsemiddle = (n1+n2+1)/2;int i=0,j=0,median=-1;int count=0;while(i<n1 && j<n2) // i and j must not exceed the length range{if(a[i]>b[j]){median = b[j];j++;count++;}else if(a[i]<=b[j]){median = a[i];i++;count++;}if(count==middle){printf("%ld",median);return 0;}}if(i==n1)printf("%ld",b[middle-n1+j-1]);else if(j==n2)printf("%ld",a[middle-n2+i-1]);return 0;}


原创粉丝点击