Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Turtle and a MEX Problem (Hard Version)

#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n, m;
    cin >> n >> m;

    map<int, vector<int>> adj;

    while (n--) {
        int len;
        cin >> len;
        vector<bool> present(len + 5, false);
        for (int i = 0; i < len; i++) {
            int ele;
            cin >> ele;
            // Reject elements greater than the length to avoid segfault.
            if (ele < present.size()) {
                present[ele] = true;
            }
        }
        int missing_count = 0;
        int u = -1, v = -1;
        for (int i = 0; i < present.size(); i++) {
            if (!present[i]) {
                missing_count++;
            }
            if (missing_count == 1 && u == -1) {
                u = i;
            }
            if (missing_count == 2) {
                v = i;
                break;
            }
        }
        adj[u].push_back(v);
    }

    for (auto &[u, vec] : adj) {
        n = max(n, u);
        for (auto &child : vec) {
            n = max(n, child);
        }
    }
    n++;

    vector<int> indp(n, -1), outdp(n, -1);
    for (int i = n - 1; i >= 0; i--) {
        indp[i] = i;
        for (auto child : adj[i]) {
            indp[i] = max(indp[i], indp[child]);
        }

        if (adj[i].size() == 1) {
            outdp[i] = i;
        } else if (adj[i].size() > 1) {
            outdp[i] = max(outdp[i], indp[i]);
        }
    }

    int lim = *max_element(outdp.begin(), outdp.end());

    vector<int> f(n);
    for (int i = 0; i < n; i++) {
        f[i] = max(indp[i], lim);
    }

    auto get_sum = [&](int n) {
        // Sum of all numbers from 1 to n.
        return 1LL * n * (n + 1) / 2;
    };

    long long res = 0;
    for (int i = 0; i <= min(n - 1, m); i++) {
        res += f[i];
    }
    if (m >= n) {
        res += get_sum(m) - get_sum(n - 1);
    }

    cout << res << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    while (t--) {
        solve();
    }
}