unittest
{
	assert( [ "3", "2 1 3" ].parse.expand.solve == 9 );
	assert( [ "4", "1 3 2 4" ].parse.expand.solve == 19 );
	assert( [ "8", "5 4 8 1 2 6 7 3" ].parse.expand.solve == 85 );
}



import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;

void main()
{
	stdin.byLineCopy.parse.expand.solve.writeln;
}

auto parse( Range )( Range input )
if( isInputRange!Range && is( ElementType!Range == string ) )
{
	input.popFront;
	auto as = input.front.split.to!( long[] );
	return tuple( as );
}

auto solve( long[] as )
{
	// 添字と値を逆にした配列を作成
	auto ais = new long[ as.length ];
	foreach( i, a; as )
	{
		ais[ a - 1 ] = i;
	}
	
	// 値が小さい順に処理
	auto ans = 0L;
	auto rbt = redBlackTree( -1L, ais.length.signed );
	foreach( a, ai; ais.enumerate( 1L ) )
	{
		// aより小さい値が含まれない最大範囲を二分検索して、パターン数を計算
		auto li = rbt.lowerBound( ai ).back;
		auto ri = rbt.upperBound( ai ).front;
		ans += a * ( ri - ai ) * ( ai - li );
		rbt.insert( ai );
	}
	return ans;
}
