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 <map> #include <set> #include <stack> #include <queue> #include <cmath> #include <ctime> #include <vector> #include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; #define INF 0x3f3f3f3f #define inf -0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define mem0(a) memset(a,0,sizeof(a)) #define mem1(a) memset(a,-1,sizeof(a)) #define mem(a, b) memset(a, b, sizeof(a)) typedef __int64 ll; const int maxn=300100; int num[maxn],maxv[maxn]; int main(){ int n,m,x,y; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++){ scanf("%d",&x); num[x]=i; maxv[i]=INF; } for(int i=1;i<=m;i++){ scanf("%d%d",&x,&y); x=num[x],y=num[y]; if(x>y) swap(x,y); maxv[x]=min(maxv[x],y); } for(int i=n-1;i>=1;i--) maxv[i]=min(maxv[i+1],maxv[i]); ll ans=0; for(int i=1;i<=n;i++){ if(maxv[i]==INF) ans=ans+n-i+1; else ans=ans+maxv[i]-i; } printf("%I64d\n",ans); return 0; }