题目描述
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it’s a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
输入描述
The first line contains two integers n and m $(1≤n≤3⋅10^5, 0≤m≤5⋅10^5)$ — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers$ p_1, p_2, …, p_n$ — the initial arrangement of pupils in the queue, from the queue start to its end (1≤$p_i$≤n, p is a permutation of integers from 1 to n). In other words, pi is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers ui, vi $(1≤u_i,v_i≤n,u_i≠v_i)$, denoting that the pupil with number ui agrees to change places with the pupil with number vi if $u_i$ is directly in front of $v_i$. It is guaranteed that if i≠j, than $v_i≠v_j $or $u_i≠u_j$. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number $p_n$.
输出描述
Print a single integer — the number of places in queue she can move forward.
思路分析
题意大概是,$n$个人排成一排,只有相邻的两个人可以换位,现在给你$m$个信息$u$和$v$,如果$u$刚好在$v$前面且相邻,那么可以换位置,现在问你最后一个人最多能够向前移动多少个位置,从后面往前遍历,如果当前这个人距离小明(最开始最后面的那个)的距离为$x$,如果他后面的可以和他交换的人数也为$x$,那么小明可以往前一步。
样例输入
3 3
3 1 2
1 2
3 1
3 2
样例输出
2
AC代码
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
#define fi first
#define se second
#define ll long long
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int INF = 0x3f3f3f3f;
const int N=1e6;
int a[N],num[N];
vi q[N];
int main(){
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
q[y].pb(x);
}
for(auto i:q[a[n-1]])num[i]++;
int ans=n-1;
for(int i=n-2;i>=0;i--){
if(i+num[a[i]]==ans)ans--;
else{
for(auto it:q[a[i]]){
num[it]++;
}
}
}
cout<<n-1-ans<<endl;
}