cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2010 · EasyComparisons

The Middle Number

Autumn Tournament (2010)

Submission name: middle.cpp

Problem summary

Given three distinct integers a, b and c, print the one that is neither smallest nor largest.

Input

Three integers a, b and c.

Output

The middle value.

Constraints

0 ≤ a, b, c ≤ 10^18; all three values are distinct.

Worked example

Original statement sample, translated without changing its numeric data.

Input

5 16 10

Output

10

Solution analysis

  1. Put the three values in an array and sort them in increasing order. The desired value is the second array element.
  2. No arithmetic on the values is necessary. Comparisons avoid overflow even near 10^18. Use long long to store each input value.
  3. For 5, 16 and 10, sorting produces 5, 10, 16. The second value is 10.

Why it works

Sorting places the unique smallest value first and the unique largest value last. The remaining, second value is therefore exactly the required middle value.

Complexity: O(1) time and O(1) extra space: the input has a fixed number of values.

Watch out. Use a 64-bit type. Do not assume the input is already sorted.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    long long values[3];
    cin>>values[0]>>values[1]>>values[2];
    // Sorting three values leaves the median at index 1.
    sort(values,values+3);
    cout<<values[1]<<'\n';
}

Source: Arena Olimpiici ↗