PAT-A 真题 – 1029 Median

发布于 / PAT-甲级 / 1 条评论

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×105) 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

题目大意:求两个序列的和序列的中位数。

这道题不能暴力联合序列,然后排序,否则会超时。

想一想,通过两个序列的元素数量,可以求出来中位数所在的位置,而给的序列又是从小到大有序的,因此只要在两个序列的前面定义个指针,不断比较大小,删掉小的元素,直到删掉中位数位置前面的所有元素即可。

代码如下:

#include <stdio.h>
#define INF 1<<31-1
#define MAXN 200010
#define MIN(a,b) (a)>(b)?(b):(a) 

int main(){
  int n1, n2;
  int p1[MAXN], p2[MAXN];
  //read seq1
  scanf("%d", &n1);
  for(int i = 0; i < n1; i++)
    scanf("%d", &p1[i]);
  p1[n1] = INF;
  //read seq2
  scanf("%d", &n2);
  for(int i = 0; i < n2; i++)
    scanf("%d", &p2[i]);
  p2[n2] = INF;
  //find
  int it1 = 0, it2 = 0, cnt = 0, mid = (n1+n2-1)/2;
  while(cnt != mid){
    if(p1[it1] < p2[it2]) it1++;
    else it2++;
    cnt++;
  }
  printf("%d", MIN(p1[it1], p2[it2]));
  return 0;
}

最近PAT网站更新,看了一眼这道题:

TIM截图20180813111314.png

内存限制1.5M......

那么就只好换一种思路,第一个序列完整的读取,第二个序列边读取边判断,判断后的数字删掉即可,使用队列来完成较为方便。

代码见柳婼同学的blog:https://www.liuchuo.net/archives/2248

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题 – 1029 Median
  1. Z

    站长,你的博客好漂亮啊