1029 Median
Posted zhanghaijie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1029 Median相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章