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<iostream>
#include<vector>

int main() {
    std::ios::sync_with_stdio(0);
    std::cin.tie(0);

    int days, first_day;
    std::cin >> days >> first_day;

    std::vector<std::vector<int>> tab(days);
    std::vector<std::vector<int>> leaves(days);

    tab[0] = std::vector<int>(first_day, 0);
    leaves[0] = std::vector<int>(first_day, 0);

    for (int day = 1; day < days; ++day) {
        int m;
        std::cin >> m;
        tab[day] = std::vector<int>(m);
        for (int i = 0; i < m; ++i) {
            std::cin >> tab[day][i];
        }
        leaves[day] = std::vector<int>(m, 0);
    }

    for (int day = days - 1; day >= 0; --day) {
        for (int i = 0; i < (int)tab[day].size(); ++i) {
            if (leaves[day][i] == 0) {
                leaves[day][i] = -1;
            }
            if (tab[day][i] != 0) {
                leaves[day - 1][tab[day][i] - 1] += std::abs(leaves[day][i]);
            }
        }   
    }

    int total = 0;
    int spare = 0;

    for (int day = 0; day < days; ++day) {
        int retrieved_after_today = 0;
        for (int i = 0; i < (int)tab[day].size(); ++i) {
            if (tab[day][i] == 0) {
                if (spare < std::abs(leaves[day][i])) {
                    total += std::abs(leaves[day][i]) - spare;
                    spare = 0;
                } else {
                    spare -= std::abs(leaves[day][i]);
                }
            }
            retrieved_after_today += leaves[day][i] == -1;
        }
        spare += retrieved_after_today;
    }
    std::cout << total << '\n';
}