[ PAT-A ] 1029 Median(C++)

题目描述

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


解题思路

题目大意
给定两个有序序列,合并他们,保证合并后仍为有序序列,找出中间位置元素
思路
刚开始思路为,合并两个有序序列,然后根据下标找出中间元素.可是如若合并两个序列,肯定会超空间,此时换一个思路,即与其找下标,不如找中间元素在合并时所在的位置,这样一来,存好第一个有序序列,对于第二个有序序列是边与第一个序列比较,边记录这些元素在合并时的位置,找到与中间元素对应的位置并输出结果即可.


代码设计
//AC代码
//zhicheng
#include<cstdio>
#include<iostream>
#include <climits>
#include<vector>
using namespace std;
//zhicheng
//August 13,2018
vector<int> a;

bool is_judge(int cn,int mid,int n)
{
    if(cn==mid) {printf("%d\n",n);return true;}
    return false;
}
int main()
{
    // freopen("1.txt","r",stdin);
    long long int tmp;int len[2],cnt=0,mid;
    scanf("%d",&len[0]);
    for(int i=0;i<len[0];i++){scanf("%lld",&tmp);tmp=min((long long int)INT_MAX,tmp);a.push_back(tmp);}
    scanf("%d",&len[1]);
    if((len[0]+len[1])%2==0) mid=(len[0]+len[1])/2-1;
    else mid=(len[0]+len[1])/2;
    int cn=0;
    while(len[1]--)
    {
        bool flg=false;
        scanf("%lld",&tmp);
        tmp=min((long long int)INT_MAX,tmp);
        while(cnt<len[0]&&a[cnt]<=tmp){is_judge(cn,mid,a[cnt]);cn++;cnt++;}
        is_judge(cn,mid,tmp);
        cn++;
    }
    if(cnt<len[0]) 
        while(cnt<len[0])
        {
            if(is_judge(cn,mid,a[cnt])) break;
            cn++;
            cnt++;
        }
    a.clear();
    return 0;
}


有关PAT (Basic Level) 的更多内容可以关注 ——> PAT-B题解


有关PAT (Advanced Level) 的更多内容可以关注 ——> PAT-A题解

铺子日常更新,如有错误请指正
传送门:代码链接 PTA题目链接 PAT-A题解

猜你喜欢

转载自blog.csdn.net/S_zhicheng27/article/details/81627754