码迷,mamicode.com
首页 > 其他好文 > 详细

1029 Median

时间:2019-01-21 13:51:51      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:count   eset   file   位置   case   时间   card   代码   middle   

1029 Median (25 分)

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 Specification:

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 (2×10?5??) 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 Specification:

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

思路
  1、这个代码我是参考柳婼的答案(https://www.liuchuo.net/archives/2248),我最初使用的是直接sort,但是有两个通不过。
下面说一下个人对正确代码理解和收获。
  2、使用sort的话空间复杂度和时间复杂度都较大,特别是空间复杂度会通不过,并且这样做没有利用好两个序列已经是有序这一条件。正确
代码使用count变量来指示每一个元素在总的序列排序后的位置,只需要计算到(m+n+1)/2即可得到答案。
技术分享图片

    下标是每个元素在排序后序列中的位置。另一个值得一提的是对a[n]进行赋值为0xffff起到了哨兵的作用,不需要再判断是否越界。

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
int a[200101];



int main()
{
    int n,m,i,maxV=0;
    cin>>n;
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
       // maxV=max(maxV,a[i]);
    }
    a[n]=0xfffff;
    cin>>m;
    int count=0,j=0;
    int mid=(m+n+1)/2;
    //cout<<mid<<endl;
    for(int i=0;i<m;i++)
    {
        int temp;
        scanf("%d",&temp);

        while(a[j]<temp)
        {

            count++;

            if(count==mid)
                cout<<a[j]<<endl;
            j++;

        }
        count++;
        if(count==mid)
            cout<<temp<<endl;
    }
    while(j<n)
    {
        count++;
        if(count==mid)
            cout<<a[j]<<endl;
        j++;
    }
    //cout<<count<<endl;
    return 0;
}

 

 

1029 Median

标签:count   eset   file   位置   case   时间   card   代码   middle   

原文地址:https://www.cnblogs.com/zhanghaijie/p/10297988.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!