您的位置:首页 > 编程语言

1029. Median (25) PAT甲级刷题

2018-02-09 15:39 381 查看
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.InputEach 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.OutputFor 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 Output13思路:参照有序表合并的思想。注意当一个表遍历完了还没到中间数的情况。#include <stdio.h>
#include <vector>
using namespace std;

int main()
{
int n1,n2;
long num;
vector<long> s1,s2;
scanf("%d",&n1);
for(int i=0;i<n1;++i){
scanf("%ld",&num);
s1.push_back(num);
}
scanf("%d",&n2);
for(int i=0;i<n2;++i){
scanf("%ld",&num);
s2.push_back(num);
}
int i1=0,i2=0,cnt=0,aim=(n1+n2+1)/2;
long ans;
while(i1<n1&&i2<n2){
++cnt;
if(s1[i1]<=s2[i2])
ans = s1[i1++];
else
ans = s2[i2++];
if(cnt==aim)
break;
}
if(cnt!=aim){
if(i1==n1)
ans = s2[i2+aim-cnt-1];
if(i2==n2)
ans = s1[i1+aim-cnt-1];
}
printf("%ld",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c 编程练习