Problem:
Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85

Solution in C# (Mono 4.6.2.0) (judge verdict: Time Limit Exceeded)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

using Pair = System.Collections.Generic.KeyValuePair<int, int>;

class Program
{
	public Program() { }

	static void Main(string[] args)
	{
		new Program().prog();
	}
	Scanner cin;
	const int MOD = 1000000007;
	const int INF = int.MaxValue;
	const double EPS = 1e-7;
	const double PI = 3.1415926536;

	void prog()
	{
		cin = new Scanner();
		int[,] dir8 = new int[8, 2] { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 }, { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 } };
		int[,] dir4 = new int[4, 2] { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };

		int N = cin.nextInt();
		int[] a = new int[N];
		int[] pos = new int[N];
		for (int i = 0; i < N; i++)
		{
			a[i] = cin.nextInt() - 1;
			pos[a[i]] = i;
		}
		List<int> used = new List<int>();
		used.Add(-1);
		long ans = (long)(pos[0] + 1) * (N - pos[0]);
		used.Add(pos[0]);
		used.Add(N);
		for (int i = 1; i < N; i++)
		{
			/*
			Console.Write("used: ");
			for (int j = 0; j < used.Count; j++)
			{
				Console.Write("{0} ", used[j]);
			}
			Console.WriteLine();
			*/
			int low = 0;
			int high = i + 1;
			while(high - low > 1)
			{
				int mid = (high + low) / 2;
				if(used[mid] > pos[i])
				{
					high = mid;
				}
				else
				{
					low = mid;
				}
			}
			//Console.WriteLine("{0} {1}", used[low], used[high]);
			ans += (long)(pos[i] - used[low]) * (used[high] - pos[i]) * (i + 1);
			used.Add(pos[i]);
			used.Sort();
			//Console.WriteLine(ans);
		}
		/*
		for (int i = 0; i < used.Count; i++)
		{
			Console.Write("{0} ",used[i]);
		}
		Console.WriteLine();
		*/
		Console.WriteLine(ans);

	}

}

class Scanner
{
	string[] s;
	int i;

	char[] cs = new char[] { ' ' };

	public Scanner()
	{
		s = new string[0];
		i = 0;
	}

	public string next()
	{
		if (i < s.Length) return s[i++];
		string st = Console.ReadLine();
		while (st == "") st = Console.ReadLine();
		s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
		i = 0;
		return next();
	}

	public int nextInt()
	{
		return int.Parse(next());
	}

	public long nextLong()
	{
		return long.Parse(next());
	}

	public double nextDouble()
	{
		return double.Parse(next());
	}
}