Lndjy and the mex
时间限制:C/C++/Rust/Pascal 3秒,其他语言6秒
空间限制:C/C++/Rust/Pascal 512 M,其他语言1024 M
64bit IO Format: %lld

题目描述

lndjy has his own unique interest in numbers. Today he came up with a multiset S consists of n non-negative integers which are not greater than n. More precisely, he has given a sequence of non-negative integers , representing that for each integer , the number of elements in S equal to i is exactly a_i. It is guaranteed that .

lndjy also showed his great interest in Combinatorics. So he wants to make sequences with S. Let the set of all different sequences which has exactly the same elements as S be A. It's easy to prove that .

What's more, lndjy loves subsegments and the mex. He defined a function f_b(l, r) on all subsegments of any given sequence as


where is the smallest non-negative integer which is not present in the multiset X. For example, , and .

Finally, he wants you to calculate the value of

输入描述:

The first line contains one integer n ().

The second line contains integers ().

输出描述:

Print a single integer, equals to .
示例1

输入

复制
1
0 1

输出

复制
0
示例2

输入

复制
2
2 0 0

输出

复制
3
示例3

输入

复制
5
2 2 1 0 0 0

输出

复制
639
示例4

输入

复制
10
4 1 2 1 2 0 0 0 0 0 0

输出

复制
3495060