1029. Median (25)-PAT

来源:互联网 发布:hl202控制卡软件下载 编辑:程序博客网 时间:2024/04/29 17:52
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

推荐指数:※

来源:http://pat.zju.edu.cn/contests/pat-a-practise/1029

merge后判断奇偶。

#include<iostream>#include<stdlib.h>#include<stdio.h>#include<string.h>using namespace std;void merge_ab(const long *a,const int len_a,const long *b,const int len_b,long *ab){int i,j,k;i=0;j=0;k=0;while(i<len_a&&j<len_b){if(a[i]<=b[j]){ab[k++]=a[i++];}else{ab[k++]=b[j++];}}if(i==len_a){while(j<len_b)ab[k++]=b[j++];}else{while(i<len_a)ab[k++]=a[i++];}}int main(){int n1,n2,i;scanf("%d",&n1);long *a=new long [n1];for(i=0;i<n1;i++)scanf("%ld",&a[i]);scanf("%d",&n2);long *b=new long [n2];for(i=0;i<n2;i++)scanf("%ld",&b[i]);long *ab=new long[n1+n2];merge_ab(a,n1,b,n2,ab);if((n1+n2)&1==1)printf("%ld\n",ab[(n1+n2+1)/2-1]);elseprintf("%ld\n",ab[(n1+n2)/2-1]);return 0;}


当然,merge的数组可以不需要,直接判断k即可。

#include<iostream>#include<stdlib.h>#include<stdio.h>#include<string.h>using namespace std;long  merge_ab(const long *a,const int len_a,const long *b,const int len_b, const int ab){int i,j,k;i=0;j=0;k=0;long tmp;while(i<len_a&&j<len_b){if(a[i]<=b[j]){tmp=a[i];k++;i++;}else{tmp=b[j];k++;j++;}if(k-1==ab)return tmp;}if(i==len_a){while(j<len_b){k++;j++;if(k-1==ab)return b[j-1];}}else{while(i<len_a){k++;i++;if(k-1==ab)return a[i-1];}}}int main(){int n1,n2,i;scanf("%d",&n1);long *a=new long [n1];for(i=0;i<n1;i++)scanf("%ld",&a[i]);scanf("%d",&n2);long *b=new long [n2];for(i=0;i<n2;i++)scanf("%ld",&b[i]);long ab;if((n1+n2)&1==1)ab=(n1+n2+1)/2-1;elseab=(n1+n2)/2-1;printf("%ld\n",merge_ab(a,n1,b,n2,ab));return 0;}


原创粉丝点击