【数据结构入门训练DAY-15】Who‘s in the Middle

文章目录

  • 前言
  • 一、题目
  • 二、解题思路
  • 总结

前言

本次训练内容:

  1. sort的训练。
  2. vector的复习。
  3. 由于题目是纯英文,所以附带些英文学习(嘻嘻)。
  4. 训练解题思维。

一、题目

FJ is surveying his herd to find the most average cow.He wants to know how much milk this 'median' cow gives:half of the cows give as much or more than the median; half give as much or less. 

Given an odd number of cows N (1 <= N < 10,000) and their milk output (1..1,000,000), find the median amount of milk  given such that at least half the cows give the same amount of milk or more and at least half give the same or less.

输入格式

* Line 1: A single integer N 
* Lines 2..N+1: Each line contains a single integer that is the milk    
                          output of one cow.

输出格式

* Line 1: A single integer that is the median milk output.

样例输入

5
2
4
1
3
5

样例输出

3

二、解题思路

        这次的题目不算难,自己翻译清楚后,它就是一个排序+取中位数。思路就是建立一个数组,然后对这个数组进行重新排序,然后输出N/2下标那个元素即可。

解法一:

#include 
using namespace std;
const int T=1e6+1;
int arr[T];//需设置全局变量
int main() {
    int N;
    cin>>N;
    for(int i=0;i>arr[i];
    }
    sort(arr, arr+N);
    cout<

解法二: 

#include 
using namespace std;
int main() {
    vector v;//建立vector
    int n,N;
    cin >> N;
    for (int i = 0; i < N; i++) {
        cin>>n;
        v.push_back(n);//插入元素
    }
    sort(v.begin(), v.end());//对容器排序
    cout<

        解法一需要注意的是,数组需要建立全局变量,否则会存在数组溢出的问题

总结

        今天的题目比较简单,就是对英文不好的朋友不太友好;这次主要就是重拾一下信心,因为最近两天的题目写的我有点难崩;后续我会再更新正常的数据结构和算法题。

你可能感兴趣的:(数据结构入门训练,数据结构,算法)