1029. Median (25)

来源:互联网 发布:淘宝店铺首页显示不全 编辑:程序博客网 时间:2024/03/29 08:30

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 145 9 10 15 16 17
Sample Output
13
sort排序  200W*log200W也就大约是4000W的样子


如果运行时间为1秒:

1000000       游刃有余

10000000     勉勉强强

100000000  很悬,仅限循环体非常简单的情况


Tip:输入用scanf


#include<iostream>  #include<cstring>  #include<cstdio>  #include<queue>  #include<stack>  #include<algorithm>  #include<vector> #include<set>using namespace std;int main(){int n;cin>>n;static long long a[2000000+10],cnt=0;for(int i=0;i<n;i++){scanf("%ld",&a[cnt++]);}cin>>n; for(int i=0;i<n;i++){scanf("%ld",&a[cnt++]);}sort(a,a+cnt);cout<<a[(cnt-1)/2];return 0;}

copy别人的代码,合并中位数

https://www.liuchuo.net/archives/2248

#include <cstdio>#include <vector>using namespace std;int main() {    int m, n, p = 0, q = 0;    scanf("%d", &m);    vector<long int> v1(m);    for(int i = 0; i < m; i++)        scanf("%ld", &v1[i]);    scanf("%d", &n);    vector<long int> v2(n);    for(int i = 0; i < n; i++)        scanf("%ld", &v2[i]);    int cnt = ((m + n) - 1) / 2;    while(cnt) {        while(p < m && q < n && v1[p] < v2[q] && cnt) {            p++;            cnt--;        }        while(p < m && q < n && v1[p] >= v2[q] && cnt) {            q++;            cnt--;        }        while(p < m && q >= n && cnt) {            p++;            cnt--;        }        while(p >= m && q < n && cnt) {            q++;            cnt--;        }    }    long int ans;    if(p < m && q < n)        ans = v1[p] < v2[q] ? v1[p] : v2[q];    else        ans = p < m ? v1[p] : v2[q];    printf("%ld", ans);    return 0;}


原创粉丝点击