原题地址:http://www.patest.cn/contests/pat-a-practise/1029
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
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 (<=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.
Output
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>
#include <algorithm>
#include <stdlib.h>
#include <cstring>
#define MAXN 1000005
using namespace std;
int N1,N2;
long int sq[MAXN*2];
long int sq1[MAXN];
long int sq2[MAXN];
/*
int cmp(const void*_a, const void*_b){
long int a = *(long int *)_a;
long int b = *(long int *)_b;
return a > b;
}
*/
int main(){
freopen("1029.txt","r",stdin);
memset(sq,-1,sizeof(sq));
scanf("%d", &N1);
for(int i = 0; i < N1; i++)
scanf("%ld", &sq1[i]);
scanf("%d", &N2);
for(int i = 0; i < N2; i++)
scanf("%ld", &sq2[i]);
int p = 0, q = 0;
int count = 0;
while(p < N1 || q < N2){
if(p >= N1){
if(count == 0) {sq[count++] = sq2[q]; q++;}
else if(sq[count-1] == sq2[q]) q++;
else {sq[count++] = sq2[q]; q++; }
}else if( q >= N2){
if(count == 0) {sq[count++] = sq1[p]; p++;}
else if(sq[count-1] == sq1[p]) p++;
else {sq[count++] = sq1[p]; p++; }
}else{
if(sq1[p] < sq2[q]){
if(count == 0) {sq[count++] = sq1[p]; p++;}
else if(sq[count-1] == sq1[p]) p++;
else {sq[count++] = sq1[p]; p++; }
}else if(sq1[p] > sq2[q]){
if(count == 0) {sq[count++] = sq2[q]; q++;}
else if(sq[count-1] == sq2[q]) q++;
else {sq[count++] = sq2[q]; q++; }
}else{
if(count == 0) {sq[count++] = sq2[q]; q++; p++;}
else if(sq[count-1] == sq2[q]) { q++; p++;}
else {sq[count++] = sq2[q]; q++; p++; }
}
}
}
// printf("%d\n",count);
// for(int i = 0; i<count;i++ ) printf("%ld \n", sq[i]);
printf("%ld\n",sq[(count*10-5)/20]);
return 0;
}