Nastya Is Buying Lunch CodeForces - 1136D (排列)

大意: 给定n排列, m个pair, 每个pair(u,v), 若u,v相邻, 且u在v左侧, 则可以交换u和v, 求a[n]最多向左移动多少

 

经过观察可以发现, 尽量先用右侧的人与a[n]交换, 这样一定最优, 然后从右往左遍历, 假设a[n]当前在$pos$, 再观察可以发现, 若$a[x]$产生贡献, 当且仅当$[x+1,pos]$都与$x$连边, 然后统计一下边数就可以$O(n+m)$了

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
//head


const int N = 1e6+10;
int n, m;
int a[N], cnt[N];
vector<int> g[N];

int main() {
	scanf("%d%d", &n, &m);
	REP(i,1,n) scanf("%d", a+i);
	REP(i,1,m) {
		int x, y;
		scanf("%d%d", &x, &y);
		g[y].pb(x);
	}
	for (auto &t:g[a[n]]) ++cnt[t];
	int ans = 0;
	PER(i,1,n-1) {
		if (n-i-ans==cnt[a[i]]) ++ans;
		else {
			for (auto &t:g[a[i]]) ++cnt[t];
		}
	}
	printf("%d\n", ans);
}

 

posted @ 2019-03-14 08:47  uid001  阅读(152)  评论(0编辑  收藏  举报