首页 > 代码库 > 题目1004:Median
题目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 145 9 10 15 16 17
- 样例输出:
13
-----------------------------------------------------------------------------------------------------------------------
思路:
- 用一维数组来存储数据。由于该数组很大,应该考虑用尽可能少的数组来实现以减少内存消耗。并且,该数组只能作为全局变量,不能再main函数定义
- scanf函数读取数据,只有按下回车时数据才会从内存到所要读取数据的变量。对于这段程序:
while(scanf("%d",&s[0])!=EOF) { for(i=1;i<=s[0];i++) scanf("%d",&s[i]);
}
输入一串数据时,按下回车之后,首先读s[0],for循环就有了结束条件了~
------------------------------------------------------------------------------------------------------------------
1 #include<stdio.h> 2 #define N 1000001 3 long s[2000002]; 4 int main(int argc, char const *argv[]) 5 { 6 int i,j,t; 7 long m,n; 8 while(scanf("%d",&s[0])!=EOF) 9 {10 m=s[0];11 for(i=1;i<=m;i++)12 scanf("%d",&s[i]);13 if(scanf("%d",&s[m+1])==EOF)14 break;15 n=s[m+1];16 for(i=m+2;i<=n+m+1;i++)17 scanf("%d",&s[i]);18 s[0]=m+n;19 for(i=m+1;i<m+n+1;i++)20 s[i]=s[i+1];21 for(i=1;i<m+n;i++)22 for(j=i+1;j<=m+n;j++) 23 if(s[i]>s[j])24 {25 t=s[i];26 s[i]=s[j];27 s[j]=t;28 }29 t=(s[0]+1)/2;30 printf("%ld\n",s[t]);31 }32 return 0;33 }