您的位置:首页 > 其它

1029. Median (25)-PAT甲级真题

2017-11-14 10:05 477 查看
1029. Median (25)

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 <cstdio>
#include <vector>
using namespace std;
int main ()
{
int m , n , p = 0 , q = 0;
long int t = 0;
scanf_s ("%d" , &m);
vector<long int> v1;
for (int i = 0; i < m; i++)
{
scanf_s ("%ld" , &t);
v1.push_back (t);
}
scanf_s ("%d" , &n);
vector<long int> v2 ;
for (int i = 0; i < n; i++)
{
scanf_s ("%ld" , &t);
v2.push_back (t);
}
int mid = ((m + n) - 1) / 2;
while (mid)
{
while (p < m && q < n && v1[p] < v2[q] && mid)
{
p++;
mid--;
}
while (p < m && q < n && v1[p] >= v2[q] && mid)
{
q++;
mid--;
}
while (p < m && q >= n && mid)
{
p++;
mid--;
}
while (p >= m && q < n && mid)
{
q++;
mid--;
}
}
long int result;
if (p < m && q < n)
result = v1[p] < v2[q] ? v1[p] : v2[q];
else
result = p < m ? v1[p] : v2[q];
printf ("%ld" , result);
return 0;
}


然后根据题目的意思是这样做的,两个数组,先找出合并后中间到底是第几个。mid=[(m+n)-1]/2,也就是说整合成一个数组后,中间值的左边也就是比他小的还有mid个,我们只要在v1,v2两个数组中从小到大找出mid个数就完成了。每找到一个需要的mid个数就-1,从数值小的那个数组的取数,取完就+1。这时要是出界了,就说明一个数组中最大的还比另一个目前下标处的小,那么中值肯定在另一个数组。如果没有人出界,当前下标两个数组中小的那个肯定是中间值的左边,另一个就是中间值。

不过我在想为啥要那么复杂的比较大小,直接把数组合并起来找出中间值不就好了么。。。。。。

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main ()
{
int m , n , p = 0 , q = 0;
long int t = 0;
scanf_s ("%d" , &m);
vector<long int> v1;
for (int i = 0; i < m; i++)
{
scanf_s ("%ld" , &t);
v1.push_back (t);
}
scanf_s ("%d" , &n);
vector<long int> v2 ;
for (int i = 0; i < n; i++)
{
scanf_s ("%ld" , &t);
v2.push_back (t);
}
vector<long int>v3;
v3.insert (v3.end () , v1.begin () , v1.end ());
v3.insert (v3.end () , v2.begin () , v2.end ());
sort (v3.begin () , v3.end ());
int mid = v3.size () / 2;
printf ("%ld" , v3.at(mid));
return 0;
}


求大佬解答困惑。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: