【CCF CSP】 201612-1 Intermediate number (100 points)

Question number: 201612-1
Question name: middle number
time limit: 1.0s
Memory limit: 256.0MB
Problem Description:
Problem Description
  In a sequence of integers a 1 , a 2 , …, an n , if there is a number, the number of integers greater than it is equal to the number of integers less than it, it is called an intermediate number. In a sequence, there may be multiple intermediate numbers with different subscripts, and the values ​​of these intermediate numbers are the same.
  Given a sequence of integers, find the value of the middle number of this sequence of integers.
input format
  The first line of input contains an integer n , the number of numbers in the sequence of integers.
  The second line contains n positive integers representing a 1 , a 2 , …, a n in order .
output format
  If the middle number of the agreed sequence exists, output the value of the middle number, otherwise output -1 to indicate that there is no middle number.
sample input
6
2 6 5 6 3 5
Sample output
5
Sample description
  There are 2 numbers smaller than 5 and 2 numbers larger than 5.
sample input
4
3 4 6 7
Sample output
-1
Sample description
  None of the 4 numbers in the sequence satisfy the definition of an intermediate number.
sample input
5
3 4 6 6 7
Sample output
-1
Sample description
  None of the 5 numbers in the sequence satisfy the definition of a middle number.
Evaluate use case size and conventions
  For all evaluation cases, 1 ≤ n ≤ 1000, 1 ≤ a i ≤ 1000.

code

C++

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void computer_min_max_sum(int &min,int &max,int middle,int n,vector<int> &number)
{
    for(int i=0;i<middle;i++)
    {
        if(number[i]<number[middle])
            min++;
    }

    for(int i=middle;i<n;i++)
    {
        if(number[i]>number[middle])
            max++;
    }
}

int main(int argc, char** argv) {
    int n,temp,middle;
    int min=0,max=0;
    int result=-1;
    vector<int> number;
    cin>>n;

    //输入 
    for(int i=0;i<n;i++)
    {
        cin>>temp;
        number.push_back(temp); 
    }
    //排序 
    stable_sort(number.begin(),number.end());
    middle=n/2; 
    //如果是偶数 
    if(n%2==0) 
    {
        //中间两个数相同 
        if(number[middle]==number[middle-1])
        {
            //计算小于数数量  大于数数量 
            computer_min_max_sum(min,max,middle,n,number);
            if(min==max)
                result=number[middle];
        }
        else
            result=-1;
    }else{//如果是奇数
            //计算小于数数量  大于数数量 
            computer_min_max_sum(min,max,middle,n,number);
            if(min==max)
                result=number[middle]; 
            else
                result=-1;
    }
    cout<<result;       
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325919613&siteId=291194637