zoukankan      html  css  js  c++  java
  • 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; 
    }
    
    
  • 相关阅读:
    寒假了
    【MFC】浏览器中快速打开常用工具
    【转】MFC隐藏进程自身(任务管理器不可见,wSysCheck等工具可见)
    【原】DIY属于自己的鼠标侧键
    coco2dx 3.4final 使用scale9sprite
    linux挂载新硬盘
    关于c语言中的结构体使用偏移量求值问题
    Linux的网卡由eth0变成了eth1,如何修复
    oracle归档管理
    exsi上虚拟因硬盘不足无法启动
  • 原文地址:https://www.cnblogs.com/woxiaosade/p/12445690.html
Copyright © 2011-2022 走看看