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; 
    }
    
    
  • 相关阅读:
    http和HTTPS的区别及SSL介绍
    cas系列(三)--HTTP和HTTPS、SSL
    cas系列(一)--cas单点登录基本原理
    修改cas登陆页面-服务器端
    rest例子
    RESTful 架构风格概述
    Java分布式应用技术架构介绍
    tomcat的server.xml详解
    Apache Shiro 快速入门教程,shiro 基础教程 (这篇文章非常好)
    fmt:formatDate标签的输出格式
  • 原文地址:https://www.cnblogs.com/woxiaosade/p/12445690.html
Copyright © 2011-2022 走看看