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 Specification:
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 (≤2×105) 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 Specification:
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
Code:
#include <iostream>
#include <vector>
#include <algorithm>
#pragma warning(disable:4996)
using namespace std;
typedef int LL;
vector<LL> va(200005);
int main()
{
int na, nb;
scanf("%d", &na);
for (int i = 0; i < na; i++)
{
scanf("%d", &va[i]);
}
scanf("%d", &nb);
int ia = 0, ib = 0, cnt = -1;
LL ca = va[ia], cb, curr = -1;
scanf("%d", &cb);
while (ia < na && ib < nb)
{
if (ca < cb)
{
curr = ca;
ia++;
if (ia < na) ca = va[ia];
cnt++;
}
else
{
curr = cb;
ib++;
if (ib < nb) scanf("%d", &cb);
cnt++;
}
if (cnt == (na + nb - 1) / 2)
{
printf("%d\n", curr);
return 0;
}
}
if (ia == na)
{
while (1)
{
curr = cb;
cnt++;
if (cnt == (na + nb - 1) / 2)
break;
}
printf("%d\n", curr);
}
else if (ib == nb)
{
printf("%d\n", va[ia + (na + nb - 1) / 2 - cnt - 1]);
}
return 0;
}
思路
这里有两个坑
- vector在空间不够的时候会动态扩展空间,默认是扩展一倍的空间,1->2->4->8…,这里如果用push_back储存数列A,第6个测试点会爆内存,如果预先规定空间,就能过。
- 题目范围给定每个数都在long int的范围内,如果vector<long long>那么会爆内存,如果vector<int>就能过(int 也在 long int的范围内)