---
id: 1082
lang: en
translation_of: index.md
source_sha256: 06d5385093637ba7bc47cca0aaca45cca3f3351a752009d1139a9e4c2f6451d8
title: "Codeforces 1136D: Nastya Is Buying Lunch — Solution"
description: "A greedy solution: scan i from n-1 down to 1, count the satisfied relations, and either transfer directly or mark the node as transferable."
tags: ["OI","Greedy","Codeforces"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "转移 rendered consistently as “transfer” (the author uses it for a pupil moving forward, not a DP transition)."
  - "可以从此被转移 rendered literally as “it can be transferred from now on”."
---

## 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.

<!--more-->

## Code

```cpp
// 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;
}
```
