Olympiad in Informatics

Codeforces 1136D: Nastya Is Buying Lunch — Solution

Main Idea

The main approach to this problem is greedy. We enumerate \(i\) from \(n-1\) down to \(1\). Let \(vis[i]\) denote whether the node numbered \(i\) can be transferred, and \(arr[i]\) the number at position \(i\); in the set of transfer relations, we look for \((i,j), vis[j]=true\) and find those \(j\). Since we transfer from back to front, the positions of the \(j\) we find are all after \(i\), which meets the transfer requirement. Then we check whether the answer transferred so far \(ans\), the number of relations satisfying the condition \(cnt\), and \(i\) sum to \(n\). If they do, that means the transfer meets the condition, and we perform the transfer directly; if not, we put the mark on this node, meaning it can be transferred from now on.

Code

// CF1136D.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 5e5 + 2000;
int arr[MAX_N], n, m, tmpx, tmpy, ans;
bool vis[MAX_N];
vector<int> cond[MAX_N];
int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d", &arr[i]);
    for (int i = 1; i <= m; i++)
        scanf("%d%d", &tmpx, &tmpy), cond[tmpx].push_back(tmpy);
    vis[arr[n]] = true;
    for (int i = n - 1; i >= 1; i--)
    {
        int cnt = 0, siz = cond[arr[i]].size();
        for (int j = 0; j < siz; j++)
            if (vis[cond[arr[i]][j]])
                cnt++;
        if (cnt + ans + i == n)
            ans++;
        else
            vis[arr[i]] = true;
    }
    printf("%d", ans);
    return 0;
}