• 数据结构与算法题目集(中文)7-53 两个有序序列的中位数 (25分)


    1.题目

    已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A​0​​,A​1​​,⋯,A​N−1​​的中位数指A​(N−1)/2​​的值,即第⌊(N+1)/2⌋个数(A​0​​为第1个数)。

    输入格式:

    输入分三行。第一行给出序列的公共长度N(0<N≤100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。

    输出格式:

    在一行中输出两个输入序列的并集序列的中位数。

    输入样例1:

    5
    1 3 5 7 9
    2 3 4 5 6
    

    输出样例1:

    4
    

    输入样例2:

    6
    -100 -10 1 1 1 1
    -50 0 2 3 4 5
    

    输出样例2:

    1

    2.代码

    #include<iostream>
    using namespace std;
    int list1[100001];
    int list2[100001];
    
    void pre(int &s, int &t)
    {
    	int m = (s + t) / 2;
    	t = m;
    }
    
    void post(int &s, int &t)
    {
    	int m = (s + t) / 2;
    	if ((s+t) % 2 == 0)
    		s = m;
    	else
    		s = m + 1;
    
    }
    
    int mid(int list1[], int s1, int t1, int list2[], int s2, int t2)
    {
    	int m1, m2;
    	if (s1 == t1&&s2 == t2)
    		return list1[s1] < list2[s2] ? list1[s1] : list2[s2];
    
    	else
    	{
    		m1 = (s1 + t1) / 2;
    		m2 = (s2 + t2) / 2;
    		if (list1[m1] == list2[m2])
    			return list1[m1];
    		if (list1[m1] < list2[m2])
    		{
    			post(s1, t1);
    			pre(s2, t2);
    			return mid(list1, s1, t1, list2, s2, t2);
    		}
    		else
    		{
    			post(s2, t2);
    			pre(s1, t1);
    			return mid(list1, s1, t1, list2, s2, t2);
    		}
    	}
    
    }
    
    int main()
    {
    	int n;
    	cin >> n;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> list1[i];
    	}
    	for(int i=0;i<n;i++)
    	{
    		cin >> list2[i];
    	}
    	printf("%d", mid(list1, 0, n - 1,list2, 0, n - 1));
    
    
    }
  • 相关阅读:
    POJ 3468 A Simple Problem with Integers
    BZOJ 4430 Guessing Camels
    POJ 2309 BST
    POJ 1990 MooFest
    cf 822B Crossword solving
    cf B. Black Square
    cf 828 A. Restaurant Tables
    Codefroces 822C Hacker, pack your bags!
    [HDU 2255] 奔小康赚大钱
    [BZOJ 1735] Muddy Fields
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12788987.html
Copyright © 2020-2023  润新知