This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define st first
#define nd second
#define pb push_back
#define pf push_front
#define _pb pop_back
#define _pf pop_front
#define lb lower_bound
#define ub upper_bound
#define bg begin
#define ed end
#define ft front
#define bk back
#define sz(x) (int)(x).size()
#define all(x) (x).bg(), (x).ed()
#define mtp make_tuple
#define ins insert
#define ers erase
#define ll long long
#define ull unsigned long long
#define db double
#define ldb long double
#define str string
#define pi pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define vpi vector<pi>
#define vpll vector<pll>
#define FOR(i, l, r) for (int i = (l); i <= (r); ++i)
#define FOS(i, r, l) for (int i = (r); i >= (l); --i)
#define FRN(i, n) for (int i = 0; i < (n); ++i)
#define FSN(i, n) for (int i = (n) - 1; i >= 0; --i)
#define EACH(i, x) for (auto &i : (x))
#define WHILE while
template<typename T> T gcd(T a, T b) { WHILE(b) { a %= b; swap(a, b); } return b; }
template<typename T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
#define file "TEST"
mt19937 rd(chrono::steady_clock::now().time_since_epoch().count());
ll rand(ll l, ll r) { return uniform_int_distribution<ll>(l, r)(rd); }
int l, r;
signed main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    // freopen(file".inp", "r", stdin);
    // freopen(file".out", "w", stdout);
    cin >> l >> r;
    vpi s;
    FRN(i, r) {
        int x;
        cin >> x;
        vi a(x, 0);
        int sum1 = 0, sum2 = 0;
        FRN(j, x) {
            cin >> a[j];
            sum2 += a[j];
        }
        FRN(j, x) {
            if (sum1 + a[j] + sum2 > l) s.pb({l - sum2 + 1, sum1 + a[j]});
            sum1 += a[j];
            sum2 -= a[j];
        }
    }
    if (s.empty()) {
        cout << 0;
        return 0;
    }
    sort(all(s));
    int ln = s[0].st, rn = s[0].nd, rs = 0;
    FRN(i, sz(s))
        if (s[i].st > rn) {
            rs += rn - ln + 1;
            ln = s[i].st;
            rn = s[i].nd;
        }
        else rn = max(rn, s[i].nd);
    rs += rn - ln + 1;
    cout << rs;
    return 0;
}
/*
11 3
2 2 3
1 7
2 4 1
*/
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |