九度[1004]-Median
2017-09-01 10:44
435 查看
九度[1004]-Median
题目描述: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 non-decreasing 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.
输入
Each input file may contain more than 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.
输出
For each test case you should output the median of the two given sequences in a line.
样例输入
4 11 12 13 14
5 9 10 15 16 17
样例输出
13
解题思路:
归并排序,要注意循环的条件。
AC代码:
#include <cstdio> typedef long long ll; const int maxn = 1000010; int N, M; ll dat1[maxn], dat2[maxn]; ll findMedian(ll dat1[], ll dat2[], int N, int M){ int flag, index, i = 0, j = 0; if((N+M)%2 == 0) flag = 0; else flag = 1; index = (N+M) / 2; ll dat[index+1]; while((i+j) <= index){ // 注意循环条件 while(dat1[i] >= dat2[j] && (i+j) <= index && j < M) { dat[i+j] = dat2[j]; j++; } while(dat1[i] <= dat2[j] && (i+j) <= index && i < N) { dat[i+j] = dat1[i]; i++; } // 注意这种特殊情况 if(j == M && (i+j) <= index && i < N){ dat[i+j] = dat1[i]; i++; } if(i == N && (i+j) <= index && j < M){ dat[i+j] = dat2[j]; j++; } } if(flag == 1) return dat[index]; else return dat[index-1]; } int main(){ freopen("C:\\Users\\Administrator\\Desktop\\test.txt", "r", stdin); while(scanf("%d", &N) != EOF){ for(int i = 0; i < N; i++){ scanf("%d", &dat1[i]); } scanf("%d", &M); for(int i = 0; i < M; i++){ scanf("%d", &dat2[i]); } printf("%lld\n", findMedian(dat1, dat2, N, M)); } fclose(stdin); return 0; }
相关文章推荐
- 九度 1004 Median
- 【九度】题目1004:Median
- 九度考研真题 浙大 2011-3浙大1004:Median
- 九度:1004<Median><中位数>
- 九度oj 题目1004:Median 【ZJU2011考研机试题3】
- 九度OJ 1004:Median
- 九度 OJ 1004:Median
- 九度OJ 1004:Median
- 九度oj-1004-Median
- 1004 Median 九度Online Judge
- 九度 题目1004:Median
- 九度——题目1004:Median
- 九度OJ : 1004 Median
- 九度 OJ 1004 median
- 【九度OJ】1004:Median
- 九度题目1004:Median
- 题目1004:Median
- 题目1004:Median
- 题目1004:Median
- 题目1004:Median