【PAT】【Advanced Level】1029. Median (25)
2017-07-20 16:45
399 查看
1029. Median (25)
时间限制1000 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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
原题链接:
https://www.patest.cn/contests/pat-a-practise/1029
思路:
二路归并
坑点:
数目为偶数,下标取下界。
归并时,注意其中之一超范围的情况
CODE:
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; long long a[1000001]; long long b[1000001]; int main() { long n1; cin>>n1; for (long i=0;i<n1;i++) scanf("%lld",&a[i]); long n2; cin>>n2; for (long i=0;i<n2;i++) scanf("%lld",&b[i]); long num=0; long s1=0; long s2=0; long re=0; long re1=0; while(1) { if (s2<n2 && a[s1]>b[s2]) { re=re1; re1=b[s2]; num++; if (num ==((n1+n2)/2+1)) break; s2++; } else if (s1<n1 && a[s1]<=b[s2]) { re=re1; re1=a[s1]; num++; if (num ==((n1+n2)/2+1)) break; s1++; } else if (s1>=n1) { re=re1; re1=b[s2]; num++; if (num ==((n1+n2)/2+1)) break; s2++; } else if (s2>=n2) { re=re1; re1=a[s1]; num++; if (num ==((n1+n2)/2+1)) break; s1++; } } if ((n1+n2)%2==0) cout<<re; else cout<<re1; return 0; }
相关文章推荐
- PAT (Advanced Level) Practise 1029 Median (25)
- PAT (Advanced Level) 1029. Median (25)
- PAT (Advanced Level) 1029. Median (25) 求两个有序数组的中位数,二分
- PAT (Advanced Level)1029. Median (25)
- 【PAT Advanced Level】1029. Median (25)
- 浙大 PAT Advanced level 1029. Median (25)
- 1029. Median (25)【排序】——PAT (Advanced Level) Practise
- 1029. Median (25) @ PAT (Advanced Level) Practise
- 【C++】PAT(advanced level)1029. Median (25)
- PAT (Advanced Level) Practise 1029 Median (25)
- PAT (Advanced Level) Practise 1029. Median (25)
- PAT (Advanced) 1029. Median (25)
- Pat(Advanced Level)Practice--1029(Median)
- PAT (Advanced Level) Practise 1016. Phone Bills (25)
- PAT (Advanced Level) Practise 1025. PAT Ranking (25)
- 1075. PAT Judge (25)【排序】——PAT (Advanced Level) Practise
- 1020. Tree Traversals (25) @ PAT (Advanced Level) Practise
- PAT 1029. Median (25) ZZZ想太多系列
- 【PAT Advanced Level】1006. Sign In and Sign Out (25)
- 【PAT Advanced Level】1017. Queueing at Bank (25)