九度oj 1004 Median 2011年浙江大学计算机及软件工程研究生机试真题

题目1004:Median

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:14162

解决:3887

题目描述:

    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 non-decreasing 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.

输入:

    Each input file may contain more than 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.

输出:

    For each test case you should output the median of the two given sequences in a line.

样例输入:
4 11 12 13 14
5 9 10 15 16 17
样例输出:
13
来源:
2011年浙江大学计算机及软件工程研究生机试真题

分析:

模拟归并:

 1 #include <cstdio>
 2 #include<algorithm>
 3 #include<iostream>
 4 using namespace std;
 5 int a[1000005],b[1000005];
 6 int main()
 7 {
 8     int n,m;
 9     while(cin>>n){
10         int i;
11         for(i=0;i<n;i++){
12             scanf("%d",&a[i]);
13         }
14         cin>>m;
15         for(i=0;i<m;i++){
16             scanf("%d",&b[i]);
17         }
18         int j=0;
19         i=0;
20         int num=(m+n-1)/2;
21         while(i<n&&j<m){
22             if(a[i]>b[j]){
23                 j++;
24                 num--;
25                 if(num<0){
26                     cout<<b[j-1]<<endl;
27                     break;
28                 }
29             }
30             else{
31                 i++;
32                 num--;
33                 if(num<0){
34                     cout<<a[i-1]<<endl;
35                     break;
36                 }
37             }
38         }
39         if(num>=0){
40             while(i<n){
41                 num--;
42                 if(num<0){
43                     cout<<a[i]<<endl;
44                     break;
45                 }
46                 i++;
47             }
48             while(j<m){
49                 num--;
50                 if(num<0){
51                     cout<<b[j]<<endl;
52                     break;
53                 }    
54                 j++;
55             }
56         }
57     }
58     return 0;
59 }

 

posted @ 2015-02-14 00:26  Deribs4  阅读(196)  评论(0编辑  收藏  举报