Permutation Substrings
Limits: 2 sec., 256 MiB
This statement was translated automatically from Ukrainian.
Marichka has a permutation \(p\) of integers from 1 to \(n\), inclusive. She is interested in the following question: how many segments \([l; r]\) (\(1 \le l \le r \le n\)) are there, for which the sequence \(p[l..r]\) is also a permutation? Help her find the answer to this question.
Input
The first line contains a single integer \(n\) — the number of elements in the given permutation.
The second line contains \(n\) integers \(p_1, p_2, ..., p_n\) — Marichka’s permutation.
Output
In a single line, print a single integer — the answer to Marichka’s question.
Constraints
\(1 \le n \le 10^5\),
for 40% of the tests, an additional constraint holds: \(n \le 10^3\).
Samples
| Input (stdin) | Output (stdout) |
|---|---|
| 7 6 3 4 1 2 7 5 | 4 |
Notes
A permutation of size \(n\) is a sequence of \(n\) integers in which each value from 1 to \(n\) appears exactly once. For example, the sequences [3, 1, 2], [1], and [1, 2, 3, 4] are permutations, while [2], [4, 1, 2], [3, 1] are not.
Submit a solution
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|
Permutation Substrings - Editorial
A permutation of length \(i\) must contain only the numbers from 1 to \(i\). For each \(i\) from 1 to \(n\), consider the first \(i\) numbers and check whether they form a contiguous segment.
Let \(l_i\) be the leftmost position among the first \(i\) numbers, and \(r_i\) the rightmost one. This means that the elements from 1 to \(i\) are within \([l_i, r_i]\). This segment is a permutation if and only if it contains only the elements from 1 to \(i\).
We know that these elements are there, but we also need to make sure there are no other elements. This is equivalent to the segment having exactly \(i\) elements. More formally, if \(r_i - l_i + 1 = i\), the segment contains no extra elements and is a permutation.
So it is enough to go over all \(i\) and find \(l_i\) and \(r_i\) for each of them, which is easy given \(l_{i - 1}\) and \(r_{i - 1}\). Then for each \(i\) we check whether \([l_i, r_i]\) is a permutation.
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|