Problem:
Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8

Solution in C# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

#region いつもの
#pragma warning disable
using System;
using System.Collections.Generic;
using System.Linq;
using IEnumerable = System.Collections.IEnumerable;
using IEnumerator = System.Collections.IEnumerator;
using BitArray = System.Collections.BitArray;
using BigInteger = System.Numerics.BigInteger;
using TextReader = System.IO.TextReader;
using static AtCoderProject.Global;
using static AtCoderProject.NumGlobal;

namespace AtCoderProject
{
    static class Global
    {
        private class ComparerReverseImpl<T> : Comparer<T> where T : IComparable<T> { public override int Compare(T y, T x) => x.CompareTo(y); public override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); }
        public static IComparer<T> ComparerReverse<T>() where T : IComparable<T> => new ComparerReverseImpl<T>();
        public static string AllLines<T>(IEnumerable<T> source) => string.Join("\n", source);
        public static string AllJoin<T>(IEnumerable<T> source) => string.Join(" ", source);
    }
    static class NumGlobal
    {
        public static BigInteger ParseBigInteger(string s)
        {
            // MonoのBigInteger.Parseが遅いので自前実装
            var res = BigInteger.Zero;
            var splited = new string[(s.Length + 7) / 8];
            for (var i = 0; i < splited.Length - 1; i++)
            {
                splited[i] = s.Substring(8 * i, 8);
            }
            splited[splited.Length - 1] = s.Substring(8 * (splited.Length - 1));
            foreach (var sp in splited)
            {
                res *= (int)Math.Pow(10, sp.Length);
                res += int.Parse(sp);
            }
            return res;
        }
        public static int BitCount(int x)
        {
            x = x - ((x >> 1) & 0x55555555);
            x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
            x = (x + (x >> 4)) & 0x0f0f0f0f;
            x = x + (x >> 8);
            x = x + (x >> 16);
            return x & 0x3f;
        }
        public static int BitCount(long x)
        {
            x = x - ((x >> 1) & 0x5555555555555555);
            x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
            x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
            x = x + (x >> 8);
            x = x + (x >> 16);
            x = x + (x >> 32);
            return (int)(x & 0x0000007f);
        }
        public static int MSB(int x)
        {
            x |= (x >> 1);
            x |= (x >> 2);
            x |= (x >> 4);
            x |= (x >> 8);
            x |= (x >> 16);
            return BitCount(x) - 1;
        }
        public static int MSB(long x)
        {
            x |= (x >> 1);
            x |= (x >> 2);
            x |= (x >> 4);
            x |= (x >> 8);
            x |= (x >> 16);
            x |= (x >> 32);
            return BitCount(x) - 1;
        }
        public static int LSB(int x)
        {
            x |= (x << 1);
            x |= (x << 2);
            x |= (x << 4);
            x |= (x << 8);
            x |= (x << 16);
            return 32 - BitCount(x);
        }
        public static int LSB(long x)
        {
            x |= (x << 1);
            x |= (x << 2);
            x |= (x << 4);
            x |= (x << 8);
            x |= (x << 16);
            x |= (x << 32);
            return 64 - BitCount(x);
        }
    }
    static class Ext
    {
        public static T[] Sort<T>(this T[] arr)
        {
            Array.Sort(arr);
            return arr;
        }
        public static T[] Reverse<T>(this T[] arr)
        {
            Array.Reverse(arr);
            return arr;
        }
        public static T[][] Chunk<T>(this T[,] source)
        {
            var len0 = source.GetLength(0);
            var len1 = source.GetLength(1);
            var res = new T[len0][];
            for (var i = 0; i < len0; i++)
            {
                res[i] = new T[len1];
                for (var j = 0; j < len1; j++)
                {
                    res[i][j] = source[i, j];
                }
            }
            return res;
        }

        public static Tuple<TSource, TMax> MaxBy<TSource, TMax>
            (this IEnumerable<TSource> source, Func<TSource, TMax> maxBySelector)
            where TMax : IComparable<TMax>
        {
            TMax max;
            TSource maxByItem;

            var e = source.GetEnumerator();
            e.MoveNext();
            maxByItem = e.Current;
            max = maxBySelector(maxByItem);
            while (e.MoveNext())
            {
                var item = e.Current;
                var next = maxBySelector(item);
                if (max.CompareTo(next) < 0)
                {
                    max = next;
                    maxByItem = item;
                }
            }
            return Tuple.Create(maxByItem, max);
        }
        public static Tuple<TSource, TMin> MinBy<TSource, TMin>
            (this IEnumerable<TSource> source, Func<TSource, TMin> minBySelector)
            where TMin : IComparable<TMin>
        {
            TMin min;
            TSource minByItem;

            var e = source.GetEnumerator();
            e.MoveNext();
            minByItem = e.Current;
            min = minBySelector(minByItem);
            while (e.MoveNext())
            {
                var item = e.Current;
                var next = minBySelector(item);
                if (min.CompareTo(next) > 0)
                {
                    min = next;
                    minByItem = item;
                }
            }
            return Tuple.Create(minByItem, min);
        }
        public static IComparer<T> Reverse<T>(this IComparer<T> comparer) => Comparer<T>.Create((x, y) => comparer.Compare(y, x));
        public static Dictionary<TKey, int> GroupCount<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => source.GroupBy(keySelector).ToDictionary(g => g.Key, g => g.Count());
        public static Dictionary<TKey, int> GroupCount<TKey>(this IEnumerable<TKey> source) => source.GroupCount(i => i);
    }
    public class ConsoleReader { private string[] ReadLineSplit() => textReader.ReadLine().Split(Array.Empty<char>(), StringSplitOptions.RemoveEmptyEntries); private string[] line = Array.Empty<string>(); private int linePosition; private TextReader textReader; public ConsoleReader(TextReader tr) { textReader = tr; } public int Int => int.Parse(String); public int Int0 => Int - 1; public long Long => long.Parse(String); public double Double => double.Parse(String); public string String { get { if (linePosition >= line.Length) { linePosition = 0; line = ReadLineSplit(); } return line[linePosition++]; } } public class SplitLine { private string[] splited; public SplitLine(ConsoleReader cr) { splited = cr.ReadLineSplit(); cr.line = Array.Empty<string>(); } public int[] Int => String.Select(x => int.Parse(x)).ToArray(); public int[] Int0 => String.Select(x => int.Parse(x) - 1).ToArray(); public long[] Long => String.Select(x => long.Parse(x)).ToArray(); public double[] Double => String.Select(x => double.Parse(x)).ToArray(); public string[] String => splited; } public SplitLine Split => new SplitLine(this); public class RepeatReader : IEnumerable<ConsoleReader> { ConsoleReader cr; int count; public RepeatReader(ConsoleReader cr, int count) { this.cr = cr; this.count = count; } public IEnumerator<ConsoleReader> GetEnumerator() => Enumerable.Repeat(cr, count).GetEnumerator(); System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); public string[] String => this.Select(cr => cr.String).ToArray(); public int[] Int => this.Select(cr => cr.Int).ToArray(); public int[] Int0 => this.Select(cr => cr.Int - 1).ToArray(); public long[] Long => this.Select(cr => cr.Long).ToArray(); public double[] Double => this.Select(cr => cr.Double).ToArray(); } public RepeatReader Repeat(int count) => new RepeatReader(this, count); }
    public class Program
    {
        [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] private ConsoleReader cr;
        public Program(ConsoleReader consoleReader) { this.cr = consoleReader; }
        static void Main() => Console.WriteLine(new Program(new ConsoleReader(Console.In)).Calc());

        #endregion
        public object Calc()
        {
            var N = cr.Int;
            a = cr.Split.Int;
            b = new SortedSet<int>(a).ToArray();
            for (int i = 0; i < b.Length; i++)
                binv[b[i]] = i;

            int l = 0;
            int r = b.Length - 1;
            while (l < r)
            {
                var m = (l + r + 1) / 2;
                if (PositionHalf(b[m])) l = m;
                else r = m - 1;
            }

            return b[l];
        }


        bool PositionHalf(int num)
        {
            var sums = new int[a.Length];
            sums[0] = a[0] >= num ? 1 : -1;
            for (int i = 1; i < sums.Length; i++)
            {
                sums[i] = sums[i - 1] + (a[i] >= num ? 1 : -1);
            }
            var cnt = sums.Count(i => i >= 0);
            var min = sums.Min();
            var max = sums.Max();
            var seg = new SegmentTree(max - min);

            for (int i = 0; i < sums.Length; i++)
            {
                var n = sums[i] - min;
                cnt += seg.Query(0, n + 1);
                seg.Increment(n);
            }


            return cnt >= ((a.Length * (a.Length + 1)) / 2 + 1) / 2;
        }

        int[] a;
        int[] b;
        Dictionary<int, int> binv = new Dictionary<int, int>();

#pragma warning disable
        [System.Diagnostics.DebuggerTypeProxy(typeof(SegmentTreeDebugView))]
        class SegmentTree
        {
            // この辺は場合によって変える
            private int defaultValue = 0;
            private int Operate(int v1, int v2)
            {
                return v1 + v2;
            }

            private int origLength;
            private int rootLength;
            private int[] tree;

            public SegmentTree(int size)
            {
                origLength = size;
                for (rootLength = 1; rootLength <= size; rootLength <<= 1) { }
                tree = Enumerable.Repeat(defaultValue, 2 * rootLength - 1).ToArray();
            }

            public void Increment(int index)
            {
                index += rootLength - 1;
                tree[index]++;
                while (index > 0)
                {
                    index = (index - 1) >> 1;
                    tree[index] = Operate(tree[index * 2 + 1], tree[index * 2 + 2]);
                }
            }

            public int Query(int fromInclusive, int toExclusive)
            {
                var leftResult = defaultValue;
                var rightResult = defaultValue;
                var l = fromInclusive + rootLength - 1;
                var r = toExclusive + rootLength - 1;

                while (l < r)
                {
                    if ((l & 1) == 0)
                        leftResult = Operate(leftResult, tree[l]);
                    if ((r & 1) == 0)
                        rightResult = Operate(tree[r - 1], rightResult);
                    l = l / 2;
                    r = (r - 1) / 2;
                }

                return Operate(leftResult, rightResult);
            }


            [System.Diagnostics.DebuggerDisplay("{value}", Name = "{key}")]
            internal class KeyValuePairs
            {
                private string key;
                private int value;

                public KeyValuePairs(string key, int value)
                {
                    this.key = key;
                    this.value = value;
                }
            }
            class SegmentTreeDebugView
            {
                private SegmentTree segmentTree;
                public SegmentTreeDebugView(SegmentTree segmentTree)
                {
                    this.segmentTree = segmentTree;
                }

                [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)]
                public KeyValuePairs[] Tree
                {
                    get
                    {
                        var keys = new List<KeyValuePairs>(segmentTree.tree.Length);
                        for (var len = segmentTree.rootLength; len > 0; len >>= 1)
                        {
                            var unit = segmentTree.rootLength / len;
                            for (var i = 0; i < len; i++)
                            {
                                var index = i + len - 1;
                                if (unit == 1)
                                    keys.Add(new KeyValuePairs($"{i}", segmentTree.tree[index]));
                                else
                                {
                                    var from = i * unit;
                                    keys.Add(new KeyValuePairs($"[{from}-{from + unit})", segmentTree.tree[index]));
                                }
                            }
                        }
                        return keys.ToArray();
                    }
                }
            }
        }


    }
}