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
#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;
}
4 11 12 13 14 5 9 10 15 16 17Sample 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;
}
相关文章推荐
- PAT甲级 1029. Median (25)
- 【PAT甲级】1029. Median (25)
- PAT 甲级 1029. Median (25)
- PAT甲级 1029. Median (25)
- PAT(甲级)1029. Median (25)
- 1029. Median (25)-PAT甲级真题(two points)
- 浙江大学PAT_甲级_1029. Median (25)
- pat甲级1029. Median (25)
- 1029. Median (25)-PAT甲级真题
- PAT甲级 1029. Median (25)
- PAT-1029 Median (25)
- PAT 1029. Median (25)
- PAT (Advanced Level) 1029. Median (25) 求两个有序数组的中位数,二分
- PAT-A1029. Median (25)
- PAT1029.Median (25)
- PAT 1029. Median (25)
- pat 1029. Median (25)
- 1029. Median (25)-PAT
- 【PAT】1029. Median (25)
- PAT 1029. Median (25)(找出俩个非递减数列的公共的中值,我用优先队列做的)