import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } real readReal() { return readToken.to!real; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } void bAdd(T)(T[] bit, int pos, T val) in { assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold"); } do { for (int x = pos; x < bit.length; x |= x + 1) { bit[x] += val; } } // sum of [0, pos) T bSum(T)(T[] bit, int pos) in { assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold"); } do { T ret = 0; for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) { ret += bit[x]; } return ret; } enum K = 5; void main() { try { for (; ; ) { const N = readInt(); auto L = new int[K]; auto R = new int[K]; auto A = new long[][](K, N - 1); foreach (k; 0 .. K) { L[k] = readInt() - 1; R[k] = readInt() - 1; foreach (i; L[k] .. R[k]) { A[k][i] = readLong(); } } const M = readInt(); auto B = new int[M]; auto S = new long[M]; foreach (m; 0 .. M) { B[m] = readInt() - 1; S[m] = readLong(); } auto ASum = new long[][](K, N); foreach (k; 0 .. K) { foreach (i; 0 .. N - 1) { ASum[k][i + 1] = ASum[k][i] + A[k][i]; } } const xs = (L ~ R).sort.uniq.array; const xsLen = cast(int)(xs.length); long ans; foreach (j; 0 .. xsLen) { const x = xs[j]; int[long] cnt; foreach (m; 0 .. M) { const k = B[m]; if (L[k] <= x && x <= R[k]) { const s = S[m] + ASum[k][x]; if (s in cnt) { ans += cnt[s]; } ++cnt[s]; } } } foreach (j; 0 .. xsLen - 1) { const l = xs[j], r = xs[j + 1]; alias Entry = Tuple!(long, "s", long, "t"); Entry[] es; foreach (m; 0 .. M) { const k = B[m]; if (L[k] <= l && r <= R[k]) { es ~= Entry(S[m] + ASum[k][l], S[m] + ASum[k][r]); } } es.sort; long[] ts; foreach (ref e; es) { ts ~= e.t; } ts = ts.sort.uniq.array; auto bit = new int[ts.length]; int tot; foreach (ref e; es) { const pos = ts.lowerBound(e.t); ans += tot - bit.bSum(pos + 1); bit.bAdd(pos, 1); ++tot; } } writeln(ans); } } catch (EOFException e) { } }