Problem:
Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136

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

using System;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using E = System.Linq.Enumerable;

partial class Solver
{
    public void Run()
    {
        var N = ni();
        var P = ni(N);

        var perm = P.Select((p, index) => new { Index = index, Value = p })
            .OrderByDescending(p => p.Value)
            .Select(p => p.Index)
            .ToArray();

        var tree = new LeftLeaningRedBlackTree<int, int>();
        long ans = 0;

        foreach (var index in perm)
        {
            var right1 = tree.IndexOfLowerBound(index);
            var right2 = right1 + 1;
            var left1 = right1 - 1;
            var left2 = right1 - 2;

            var left1Area = 1;
            var right1Area = 1;
            var left2Area = 0;
            var right2Area = 0;

            if (left1 >= 0) left1Area = index - tree.At(left1);
            else left1Area = index + 1;

            if (right1 < tree.Count) right1Area = tree.At(right1) - index;
            else right1Area = P.Length - index;

            if (left2 >= 0) left2Area = tree.At(left1) - tree.At(left2);
            else if (left1 >= 0) left2Area = left1 + 1;

            if (right2 < tree.Count) right2Area = tree.At(right2) - tree.At(right1);
            else if (right1 < tree.Count) right2Area = P.Length - tree.At(right1);

            ans += (left1Area * right2Area + left2Area * right1Area) * 1L * P[index];

            tree.Add(index, index);
        }
        cout.WriteLine(ans);
    }
}



public partial class LeftLeaningRedBlackTree<TKey, TValue>
{
    private Node root = null;
    private readonly IComparer<TKey> _comparer;

    public LeftLeaningRedBlackTree() : this(Comparer<TKey>.Default)
    {
    }

    public LeftLeaningRedBlackTree(IComparer<TKey> comparer)
    {
        _comparer = comparer;
    }

    public TValue this[TKey key]
    {
        get { return Find(key); }
        set { Add(key, value); }
    }

    public TValue Find(TKey key)
    {
        return Find(root, key);
    }

    public int Count { get { return root == null ? 0 : root.Count; } }

    private TValue Find(Node h, TKey key)
    {
        while (h != null)
        {
            int cmp = _comparer.Compare(key, h.Key);
            if (cmp == 0)
            {
                return h.Value;
            }
            h = (cmp < 0) ? h.Left : h.Right;
        }
        throw new KeyNotFoundException();
    }

    public int IndexOfLowerBound(TKey key)
    {
        var node = root;
        int index = 0;
        while (node != null)
        {
            int leftCount = node.Left == null ? 0 : node.Left.Count;
            int cmp = _comparer.Compare(key, node.Key);
            if (cmp == 0)
            {
                index += leftCount;
                break;
            }
            else if (cmp < 0)
            {
                node = node.Left;
            }
            else
            {
                index += leftCount + 1;
                node = node.Right;
            }
        }
        return index;
    }

    public TValue At(int index)
    {
        var node = root;
        while (node != null)
        {
            int leftCount = node.Left == null ? 0 : node.Left.Count;
            if (index == leftCount) return node.Value;
            if (index < leftCount)
            {
                node = node.Left;
            }
            else
            {
                node = node.Right;
                index -= leftCount + 1;
            }
        }
        throw new ArgumentOutOfRangeException("index");
    }

    public void Add(TKey key, TValue value)
    {
        root = Add(root, key, value);
        root.Color = Node.BLACK;
    }

    private Node Add(Node h, TKey key, TValue value)
    {
        if (h == null)
        {
            return new Node(key, value);
        }

        if (IsRed(h.Left) && IsRed(h.Right))
        {
            ColorFlip(h);
        }

        int cmp = _comparer.Compare(key, h.Key);
        if (cmp == 0)
        {
            h.Value = value;
        }
        else if (cmp < 0)
        {
            h.Left = Add(h.Left, key, value);
            h.FixCount();
        }
        else
        {
            h.Right = Add(h.Right, key, value);
            h.FixCount();
        }

        if (IsRed(h.Right) && !IsRed(h.Left))
        {
            h = RotateLeft(h);
        }

        if (IsRed(h.Left) && IsRed(h.Left.Left))
        {
            h = RotateRight(h);
        }

        return h;
    }

    public void RemoveMin()
    {
        root = RemoveMin(root);
        if (root != null)
        {
            root.Color = Node.BLACK;
        }
    }

    private Node RemoveMin(Node h)
    {
        if (h.Left == null)
        {
            return null;
        }

        if (!IsRed(h.Left) && !IsRed(h.Left.Left))
        {
            h = MoveRedLeft(h);
        }

        h.Left = RemoveMin(h.Left);
        h.FixCount();
        return FixUp(h);
    }

    public void Remove(TKey key)
    {
        root = Remove(root, key);
        if (root != null)
        {
            root.Color = Node.BLACK;
        }
    }

    private Node Remove(Node h, TKey key)
    {
        if (_comparer.Compare(key, h.Key) < 0)
        {
            if (h.Left == null)
            {
                throw new KeyNotFoundException("key");
            }

            if (!IsRed(h.Left) && !IsRed(h.Left.Left))
            {
                h = MoveRedLeft(h);
            }
            h.Left = Remove(h.Left, key);
            h.FixCount();
        }
        else
        {
            if (IsRed(h.Left))
            {
                h = RotateRight(h);
            }

            if (h.Right == null)
            {
                if (_comparer.Compare(key, h.Key) == 0)
                {
                    return null;
                }

                throw new KeyNotFoundException("key");
            }

            if (!IsRed(h.Right) && !IsRed(h.Right.Left))
            {
                h = MoveRedRight(h);
            }

            if (_comparer.Compare(key, h.Key) == 0)
            {
                h.Value = Find(h.Right, Min(h.Right).Key);
                h.Key = Min(h.Right).Key;
                h.Right = RemoveMin(h.Right);
                h.FixCount();
            }
            else
            {
                h.Right = Remove(h.Right, key);
                h.FixCount();
            }
        }

        return FixUp(h);
    }

    private static Node MoveRedLeft(Node h)
    {
        ColorFlip(h);

        if (IsRed(h.Right.Left))
        {
            h.Right = RotateRight(h.Right);
            h.FixCount();
            h = RotateLeft(h);
            ColorFlip(h);
        }

        return h;
    }

    private static Node MoveRedRight(Node h)
    {
        ColorFlip(h);

        if (IsRed(h.Left.Left))
        {
            h = RotateRight(h);
            ColorFlip(h);
        }

        return h;
    }

    static private Node RotateLeft(Node h)
    {
        Node x = h.Right;
        h.Right = x.Left;
        x.Left = h;

        x.Color = h.Color;
        h.Color = Node.RED;
        h.FixCount();
        x.FixCount();
        return x;
    }

    private static Node RotateRight(Node h)
    {
        Node x = h.Left;
        h.Left = x.Right;
        x.Right = h;

        x.Color = h.Color;
        h.Color = Node.RED;
        h.FixCount();
        x.FixCount();
        return x;
    }

    private static bool IsRed(Node h)
    {
        return h != null && h.Color == Node.RED;
    }

    static private void ColorFlip(Node h)
    {
        h.Color = !h.Color;
        h.Left.Color = !h.Left.Color;
        h.Right.Color = !h.Right.Color;
    }

    static private Node Min(Node h)
    {
        while (h.Left != null)
        {
            h = h.Left;
        }
        return h;
    }

    static private Node FixUp(Node h)
    {
        if (IsRed(h.Right))
        {
            h = RotateLeft(h);
        }

        if (h.Left != null && IsRed(h.Left) && IsRed(h.Left.Left))
        {
            h = RotateRight(h);
        }

        if (IsRed(h.Left) && IsRed(h.Right))
        {
            ColorFlip(h);
        }

        return h;
    }

    private class Node
    {
        public static readonly bool RED = true;
        public static readonly bool BLACK = false;
        public TKey Key;
        public TValue Value;
        public bool Color = RED;
        public Node Left = null;
        public Node Right = null;
        public int Count = 1;
        public Node(TKey key, TValue value)
        {
            this.Key = key;
            this.Value = value;
        }

        public void FixCount()
        {
            this.Count = 1;
            if (Left != null) Count += Left.Count;
            if (Right != null) Count += Right.Count;
        }
    }
}

// PREWRITEN CODE BEGINS FROM HERE
partial class Solver : Scanner
{
    public static void Main(string[] args)
    {
#if LOCAL
        new Solver(Console.In, Console.Out).Run();
#else
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver(Console.In, Console.Out).Run();
        Console.Out.Flush();
#endif
    }

#pragma warning disable IDE0052
    private readonly TextReader cin;
    private readonly TextWriter cout;
#pragma warning restore IDE0052

    public Solver(TextReader reader, TextWriter writer)
        : base(reader)
    {
        this.cin = reader;
        this.cout = writer;
    }
    public Solver(string input, TextWriter writer)
        : this(new StringReader(input), writer)
    {
    }

#pragma warning disable IDE1006
#pragma warning disable IDE0051
    private int ni() { return NextInt(); }
    private int[] ni(int n) { return NextIntArray(n); }
    private long nl() { return NextLong(); }
    private long[] nl(int n) { return NextLongArray(n); }
    private double nd() { return NextDouble(); }
    private double[] nd(int n) { return NextDoubleArray(n); }
    private string ns() { return Next(); }
    private string[] ns(int n) { return NextArray(n); }
#pragma warning restore IDE1006
#pragma warning restore IDE0051
}

public static class LinqPadExtension
{
    static public T Dump<T>(this T obj)
    {
#if LOCAL
        return LINQPad.Extensions.Dump(obj);
#else
        return obj;
#endif
    }
}
public class Scanner
{
    private readonly TextReader Reader;
    private readonly Queue<string> TokenQueue = new Queue<string>();
    private readonly CultureInfo ci = CultureInfo.InvariantCulture;

    public Scanner()
        : this(Console.In)
    {
    }

    public Scanner(TextReader reader)
    {
        this.Reader = reader;
    }

    public int NextInt() { return int.Parse(Next(), ci); }
    public long NextLong() { return long.Parse(Next(), ci); }
    public double NextDouble() { return double.Parse(Next(), ci); }
    public string[] NextArray(int size)
    {
        var array = new string[size];
        for (int i = 0; i < size; i++) array[i] = Next();
        return array;
    }
    public int[] NextIntArray(int size)
    {
        var array = new int[size];
        for (int i = 0; i < size; i++) array[i] = NextInt();
        return array;
    }

    public long[] NextLongArray(int size)
    {
        var array = new long[size];
        for (int i = 0; i < size; i++) array[i] = NextLong();
        return array;
    }

    public double[] NextDoubleArray(int size)
    {
        var array = new double[size];
        for (int i = 0; i < size; i++) array[i] = NextDouble();
        return array;
    }

    public string Next()
    {
        if (TokenQueue.Count == 0)
        {
            if (!StockTokens()) throw new InvalidOperationException();
        }
        return TokenQueue.Dequeue();
    }

    public bool HasNext()
    {
        if (TokenQueue.Count > 0)
            return true;
        return StockTokens();
    }
    static readonly char[] _separator = new[] { ' ' };
    private bool StockTokens()
    {
        while (true)
        {
            var line = Reader.ReadLine();
            if (line == null) return false;
            var tokens = line.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length == 0) continue;
            foreach (var token in tokens)
                TokenQueue.Enqueue(token);
            return true;
        }
    }
}