You are given a permutation p of length n. Also you are given m foe pairs (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi).
Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).
Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair(3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair.
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the length of the permutation p and the number of foe pairs.
The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p.
Each of the next m lines contains two integers (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi) — the i-th foe pair. Note a foe pair can appear multiple times in the given list.
Print the only integer c — the number of different intervals (x, y) that does not contain any foe pairs.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
4 2 1 3 2 4 3 2 2 4
5
9 5 9 7 2 3 1 4 6 5 8 1 6 4 5 2 7 7 2 2 7
20
In the first example the intervals from the answer are (1, 1), (1, 2), (2, 2), (3, 3) and (4, 4).
给你一个n的排列(n<=3*10^5),然后给你m个禁止的组合(m<=3*10^5),问你有多少个区间不包含任何一个禁止的组合。
思路:
1.O(n+m)
考虑每个位置,他的最远的右区间是多少,我们可以在输入m个禁止组合的时候,维护位置较小的那个数的最远位置,这样我们便知道了那些出现过的每个较小位置对应的最右位置。
然后逆序更新一遍每个位置的最右位置就行了,因为如果在他右边的位置的最远位置已经确定了,那么在他左边的最远位置的数也一定不能取到这个最远位置。
2.O(nlogn)
对禁止区间按l从小到大排序,逆序加入禁止区间,维护最右边的最小值。
#include