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.

    Sample Input:

    4 11 12 13 14
    5 9 10 15 16 17
    

    Sample Output:

    13
    
     注意点:因为测试点的输入数据可能非常大, 所以一定要用scanf, 否则会超时
     1 #include<iostream>
     2 #include<vector>
     3 using namespace std;
     4 int main(){
     5   int n, i, m;
     6   cin>>n;
     7   vector<int> v(n+1);
     8   for(i=0; i<n; i++) scanf("%d", &v[i]);
     9   cin>>m;
    10   int cnt=0, idx=0, ans, mid=(m+n+1)/2;
    11   for(i=0; i<m; i++){
    12     int num;
    13     scanf("%d", &num);
    14     while(idx<n&&v[idx]<num){
    15       cnt++;
    16       if(cnt==mid) cout<<v[idx]<<endl;
    17       idx++;
    18     }
    19     cnt++;
    20     if(cnt==mid) cout<<num<<endl;
    21   }
    22   while(idx<n){
    23     cnt++;
    24     if(cnt==mid)  cout<<v[idx]<<endl;
    25     idx++;
    26   }
    27   return 0;
    28 }
     
     
  • 相关阅读:
    链表--反转链表(leetcode 206
    链表--重排链表(leetcode 143
    链表--删除链表中的结点(leetcode 237
    链表--K个一组反转链表(leetcode 25
    链表--相交链表(leetcode 160
    链表--两数相加II(leetcode 445
    链表--复制含有随机指针节点的链表(leetcode138
    链表--回文链表(leetcode234
    链表--环形链表(leetcode 141,142
    链表--分隔链表(leetcode86
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9573161.html
Copyright © 2011-2022 走看看