USACO 2020 Silver US Open P2: Cereal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;

#define f first
#define s second
int N, M;

const int MaX = 100001;
vector<int> occ(MaX, 0);
int ans = 0;
vector<pair<int, int>> cows(MaX);

int main() {
    ifstream cin("cereal.in");
    ofstream cout("cereal.out");
    cin >> N >> M;

    for (int i = 0; i < N; i++) {
        int F, S;
        cin >> F >> S;
        cows[i].f = F;
        cows[i].s = S;
    }

    vector<int> ansVec(N);

    for (int i = N - 1; i >= 0; i--) {
        int pos = cows[i].f;
        int j = i;

        while (true) {
            if (occ[pos] == 0) {
                occ[pos] = j;
                ans++;
                break;
            }
            else if (occ[pos] < j) {
                break;
            }
            else {
                int next = occ[pos];
                occ[pos] = j;
                if (pos == cows[next].s) {
                    break;
                }
                j = next;
                pos = cows[next].s;
            }
        }
        ansVec[i] = ans;

    }

    for (int i = 0; i < N; i++) {
        cout << ansVec[i] << endl;
    }
}