#include using namespace std; using LL = long long int; #define incID(i, l, r) for(int i = (l) ; i < (r); ++i) #define incII(i, l, r) for(int i = (l) ; i <= (r); ++i) #define decID(i, l, r) for(int i = (r) - 1; i >= (l); --i) #define decII(i, l, r) for(int i = (r) ; i >= (l); --i) #define inc(i, n) incID(i, 0, n) #define inc1(i, n) incII(i, 1, n) #define dec(i, n) decID(i, 0, n) #define dec1(i, n) decII(i, 1, n) #define inID(v, l, r) ((l) <= (v) && (v) < (r)) #define inII(v, l, r) ((l) <= (v) && (v) <= (r)) #define PB push_back #define EB emplace_back #define MP make_pair #define FI first #define SE second #define ALL(v) v.begin(), v.end() #define RALL(v) v.rbegin(), v.rend() auto setmin = [](auto & a, auto b) { return (b < a ? a = b, true : false); }; auto setmax = [](auto & a, auto b) { return (b > a ? a = b, true : false); }; auto setmineq = [](auto & a, auto b) { return (b <= a ? a = b, true : false); }; auto setmaxeq = [](auto & a, auto b) { return (b >= a ? a = b, true : false); }; auto fl = [](auto a, auto b) { assert(b != 0); return a / b - (a % b != 0 && ((a >= 0) != (b >= 0)) ? 1 : 0); }; auto ce = [](auto a, auto b) { assert(b != 0); return a / b + (a % b != 0 && ((a >= 0) == (b >= 0)) ? 1 : 0); }; auto mo = [](auto a, auto b) { assert(b != 0); a %= b; if(a < 0) { a += abs(b); } return a; }; LL gcd(LL a, LL b) { return (b == 0 ? a : gcd(b, a % b)); } LL lcm(LL a, LL b) { return a / gcd(a, b) * b; } #define bit(b, i) (((b) >> (i)) & 1) #define SI(v) static_cast(v.size()) #define RF(e, v) for(auto & e: v) #define until(e) while(! (e)) #define if_not(e) if(! (e)) #define ef else if #define UR assert(false) // ---- ---- bool all = true; // 現在地と宛先の座標が等しい郵便物も回収する必要があるか int f(vector const & v) { int n = SI(v); assert(n % 2 == 0); vector d(n - 1), sl(n), sr(n); inc(i, n - 1) { if(i % 2 == 0) { d[i] = 2 * (v[i + 1] - v[i]); } } inc(i, n - 1) { sl[i + 1] = sl[i] + d[i]; } dec(i, n - 1) { sr[i] = sr[i + 1] + d[i]; } inc(i, n) { setmin(sl[i], v[i] - v.front()); } inc(i, n) { setmin(sr[i], v.back() - v[i]); } int ans = 1e9; inc(i, n) { setmin(ans, sl[i] + sr[i]); } assert(ans <= 2 * (v.back() - v.front())); return ans + v.back() - v.front(); } int main() { int n, m; cin >> n >> m; vector L(n + 1), R(n + 1); int mi = n, ma = -1; inc(i, m) { int x, d; cin >> x >> d; inc(j, d) { int y; cin >> y; if(all || x != y) { setmin(mi, min(x, y)); setmax(ma, max(x, y)); } if(y < x) { L[y]++; L[x]--; } if(x < y) { R[x]++; R[y]--; } } } inc(i, n) { L[i + 1] += L[i]; R[i + 1] += R[i]; if(L[i] != 0) { L[i] = 1; } if(R[i] != 0) { R[i] = 1; } } assert(L[n] == 0); assert(R[n] == 0); vector vl, vr; int pl = 0, pr = 0; incII(i, 0, n) { if(i == mi || i == ma) { vl.PB(i); vl.PB(i); vr.PB(i); vr.PB(i); } if(L[i] != pl) { vl.PB(i); } if(R[i] != pr) { vr.PB(i); } pl = L[i]; pr = R[i]; } cout << min(f(vl), f(vr)) << endl; return 0; }