• PAT 1029 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 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.

    思路

    合并有序的序列

    代码

    #include <stdio.h>
    #include <string>
    #include <stdlib.h>
    #include <iostream>
    #include <vector>
    #include <string.h>
    #include <algorithm>
    #include <cmath>
    #include <map>
    #include <queue>
    #include <stack>
    #include <functional>
    #include <limits.h> 
    using namespace std;
    
    long long a1[200000 + 10];
    long long a2[200000 + 10];
    long long ans[500000 + 10];
    int main() {
    	int N, M;
    	scanf("%d", &N);
    	for(int i = 0; i < N; i++)		scanf("%lld", a1 + i);
    	scanf("%d", &M);
    	for(int i = 0; i < M; i++)		scanf("%lld", a2 + i);
    	int pos = 0;
    	int i = 0, j = 0;
    	while(i < N || j < M){
    		if(pos > N + M / 2)	break;
    		if(i < N && j < M)	ans[pos++] = a1[i] < a2[j] ? a1[i++] : a2[j++];
    		else if (i < N)		ans[pos++] = a1[i++];			
    		else				ans[pos++] = a2[j++];
    	}
    	if((N + M) % 2 == 0)	cout << ans[(N + M) / 2 - 1] << endl;
    	else					cout << ans[(N + M) >> 1] << endl;
    	return 0; 
    }
    
    
  • 相关阅读:
    解析 AJAX 返回回来的 xml字符串
    JS 与 后台如何获取 Cookies
    鼠标上下滚轮事件
    MVC Control 返回各种数据
    ildasm 查看程序集 里面的图标的意思
    对象的序列化和反序列化 itprobie
    文件上传通用类 itprobie
    文件下载的四种方式 itprobie
    委托事件的实际运用 itprobie
    使用NPOI实现excel的导入导出 itprobie
  • 原文地址:https://www.cnblogs.com/woxiaosade/p/12445690.html
Copyright © 2020-2023  润新知