Codeforces Round #546 (Div. 2) D. Nastya Is Buying Lunch

题意:

长度为n的数组{pi},m对关系(a,b),如果a正好在数组中位于b的前一个位置,则可以交换a和b,问最多可以让pn的位置往前移动多少

题解:

如果pk能与pn交换并更新答案,它肯定能和pn以及中间所有不能更新答案的位置的数字交换,统计这样可以更新答案的pk的个数

#include <bits/stdc++.h>
//#pragma comment(linker, ”/STACK:36777216“)
           
using namespace std;
           
typedef long long ll;
#define mp make_pair
#define pb push_back
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define db long double

int n, m;
vector<int> a, was;
vector<vector<int> > g;

int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    ios_base::sync_with_stdio(0); cin.tie(0);
    cin >> n >> m;
    a.resize(n);
    g.resize(n);
    was.resize(n);
    for (int i = 0; i < n; i++) cin >> a[i], a[i]--;
    for (int i = 0; i < m; i++){
        int w1, w2;
        cin >> w1 >> w2;
        w1--; w2--;
        g[w1].pb(w2);
    }

    reverse(all(a));
    int ans = 0;

    for (int i = 0; i < n; i++) was[i] = 0;
    was[a[0]] = 1;
    int cnt = 1;
    for (int i = 1; i < n; i++){
        int cnt2 = 0;
        for (int to : g[a[i]]){
            if (was[to]) cnt2++;
        }
        if (cnt == cnt2){
            ans++;
        } else {
            was[a[i]] = 1;
            cnt++;
        }
    }

    cout << ans;
}

猜你喜欢

转载自www.cnblogs.com/hyfer/p/10534558.html