Educational Codeforces Round 10 C. Foe Pairs —— 后缀和

题目链接:http://codeforces.com/problemset/problem/652/C


C. Foe Pairs
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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.

Output

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.

Examples
input
4 2
1 3 2 4
3 2
2 4
output
5
input
9 5
9 7 2 3 1 4 6 5 8
1 6
4 5
2 7
7 2
2 7
output
20
Note

In the first example the intervals from the answer are (1, 1)(1, 2)(2, 2)(3, 3) and (4, 4).




题解:

1.pos[val]记录val的下标,lim[l]记录以l为左端点,其敌人作为右端点的最小下标。

2.为使得每个间隔不出现死敌,所以需要对lim[l]进行修改,做法是从右往左更新lim[l]的最小值。



代码如下:

#include
using namespace std;
typedef long long LL;
const double eps = 1e-6;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 3e5+10;

int n, m;
int pos[maxn], lim[maxn];

void init()
{
    scanf("%d%d",&n,&m);
    for(int i = 1; i<=n; i++)
    {
        int v;
        scanf("%d",&v);
        pos[v] = i;
        lim[i] = n + 1;
    }
}

void solve()
{
    for(int i = 1; i<=m; i++)
    {
        int x, y;
        scanf("%d%d",&x,&y);
        int l = pos[x];
        int r = pos[y];
        if(l>r) swap(l,r);
        lim[l] = min(lim[l], r);
    }

    for(int i = n-1; i>=1; i--)
        lim[i] = min(lim[i], lim[i+1]);

    LL ans = 0;
    for(int i = 1; i<=n; i++)
        ans += 1LL*lim[i] - 1LL*i;
    cout<


你可能感兴趣的:(前缀和,&,后缀和)