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 (Easy Version)

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

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

    // sm[i] denotes the second missing element of the i-th list.
    vector<int> sm;

    while (n--) {
        int len;
        cin >> len;
        vector<bool> present(len + 2, 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;
        for (int i = 0; i < present.size(); i++) {
            if (!present[i]) {
                missing_count++;
            }
            if (missing_count == 2) {
                sm.push_back(i);
                break;
            }
        }
    }

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

    int stop = min(m, lim);
    long long res = 1LL * (stop + 1) * lim;
    if (m > lim) {
        res += get_sum(m) - get_sum(lim);
    }

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

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

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