Educational Codeforces Round 10C Foe Pairs

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.

Example
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).

求符合条件的区间的个数,要求区间内不能有列出的点对,给出的点对是数值,而区间是下标。
先枚举起点,再找最长区间长度。一开始想的是先枚举长度再枚举起点,太耗时间。
将点对转换成下标后按照右坐标从小到大排序,然后从左到右枚举起点,点对中左坐标在起点左边的直接排除,因为不可能被区间包含,所以排除后的第一个点对的右坐标就是区间的极限长度,由于已经包含了这个点对,更长的区间一定不符合条件。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
int mo[4][2]={0,1,1,0,0,-1,-1,0};
const int MAXN=0x3f3f3f3f;
const int sz=600005;
int n,m;
int a[sz],pos[sz],vis[sz];
struct node{
    int len,l,r;
}edge[sz];
bool cmp(node x,node y){
    if(x.r==y.r){
        return x.lelse{
        return x.rvoid ss(){
    int j=1;
    for(int i=1;i<=n;i++){
        while(edge[j].lif(j<=m)
            ans+=edge[j].r-i;
        else
            ans+=n+1-i;
        //cout<
    }
}
int main()
{
    int x,y,len,pre,cot;
    //freopen("C:\\Users\\Administrator\\Desktop\\r.txt","r",stdin);
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            pos[a[i]]=i;
        }
        memset(vis,0,sizeof(vis));
        ans=0;
        for(int i=1;i<=m;i++){
            scanf("%d%d",&x,&y);
            x=pos[x];y=pos[y];
            if(x>y) swap(x,y);
            edge[i].l=x;
            edge[i].r=y;
        }
        sort(edge+1,edge+1+m,cmp);
        ss();
        printf("%I64d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(脑洞题)