您的位置:首页 > 其它

PAT 1029. Median (25)

2015-08-07 23:47 525 查看

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

输入需要采用scanf输入


#include <iostream>
#include <cstdio>

using namespace std;

long seq1[1000000], seq2[1000000];
long finalseq[2000000];

int main()
{
int n1, n2;
cin >> n1;
for (int i = 0; i < n1; i++)
scanf("%ld", &seq1[i]);
cin >> n2;
for (int i = 0; i < n2; i++)
scanf("%ld", &seq2[i]);

int i = 0, j = 0, k = 0;
while (i < n1 || j < n2)
{
if (i == n1)    //only seqence1
finalseq[k++] = seq2[j++];
else if (j == n2)    //only seqence2
finalseq[k++] = seq1[i++];
else if (seq1[i] < seq2[j])
finalseq[k++] = seq1[i++];
else if (seq1[i]>seq2[j])
finalseq[k++] = seq2[j++];
else
{
finalseq[k++] = seq1[i++];
j++;
}
}
cout << finalseq[(k - 1) / 2];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: