Explanation
Sorting the entire array with just one operation seems a little intimidating.
The way to simplify this is to look at adjacent pairs of elements instead. If for each pair of elements and we made it so that , then this would imply the entire array being sorted!
There's still a little casework after noticing this, though:
- If , we know . Intuitively, this means that we can't put past the middle of and , as that would make closer to than it is to .
- If , we similarly have .
- Otherwise, both are equal and it doesn't matter what value of we choose.
All these pairs limit to a (possibly empty) range of numbers. We keep track of this range as we go along the array and output any element in it at the end.
Implementation
Time Complexity:
C++
#include <algorithm>#include <cstdint>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;/**
Java
import java.io.*;import java.util.*;public class AbsoluteSorting {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));int testNum = Integer.parseInt(read.readLine());for (int t = 0; t < testNum; t++) {int len = Integer.parseInt(read.readLine());int[] arr = Arrays.stream(read.readLine().split(" "))
Python
def ceildiv(a, b):return -(a // -b)for _ in range(int(input())):len_ = int(input())arr = [int(i) for i in input().split()]assert len(arr) == len_at_least = -float("inf")
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!