C. Foe Pairs

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

题意:题目给出一个1到n的某一个排列,有m个二维点。问这n个数形成的所有子区间中,不包含m个点中任何一个的子区间有多少?

题解:注意到二维点也是在1-n中,所以看到排列,自然应该想到可能跟数的位置有关。对于每一个二维点,它其实形成了一个区间。所以原问题就转

换为区间包含问题。这题的解法很多,上述解法我认为是最好的。我自己写了个最笨的做法。。。

AC代码:

#include <iostream>
#include <vector>
#include <map>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

typedef long long ll;
const int N = 3e5 + 10;
vector<int> G[N];
int mp[N],vis[N],a[N];

int check(int u)
{
    int cnt = 0;
    for(int i = 0; i < G[u].size(); ++i)
    {
        int v = G[u][i];
        if(mp[v] && vis[v] == 0)
        {
            vis[v] = 1;
            cnt++;
        }
    }
    return cnt;
}

void solve()
{
    int n,m;
    cin >> n >> m;
    for(int i = 1; i <= n; ++i) scanf("%d",&a[i]);
    for(int i = 1; i <= m; ++i)
    {
        int u,v;
        scanf("%d %d",&u,&v);
        if(u > v) swap(u,v);
        G[u].push_back(v);
        G[v].push_back(u);
    }
    long long ans = 1LL * n * (n + 1) / 2;
    int L = 1;
    for(int R = 1; R <= n; ++R)
    {
        int cnt = check(a[R]);
        while(cnt)
        {
            ans -= n - R + 1;
            if(vis[a[L]])
            {
                cnt--;
                vis[a[L]] = 0;
            }
            mp[a[L]] = 0;
            L++;
        }
        mp[a[R]] = 1;
    }
    cout << ans << endl;
}


int main()
{
    solve();
    return 0;
}
点赞