#include using namespace std; const int MX = 1000000; vector a[MX]; int main() { int testCases, totalSum = 0; scanf("%d", &testCases); assert(testCases >= 1 && testCases <= MX); while (testCases--) { int n, sumM = 0; ignore = scanf("%d", &n); assert(n >= 1 && n <= MX); for (int i = 0; i < n; i++) { a[i].clear(); } for (int i = 0, m; i < n; i++) { ignore = scanf("%d", &m); sumM += m; assert(m >= 1 && m <= MX); assert(sumM <= MX); for (int j = 0, x; j < m; j++) { ignore = scanf("%d", &x); assert(x >= 1 && x <= (int) 1e9); a[i].push_back(x); } } totalSum += sumM; vector> funcs = {{0, 0}}; for (long long i = 0; i < n; i++) { decltype(funcs) pos, neg; auto cmp = [](auto x, auto y) { return x.second < y.second; }; sort(funcs.begin(), funcs.end(), cmp); int mx = *max_element(a[i].begin(), a[i].end()); neg.emplace_back(-1 * mx * i, 0); for (auto f : funcs) { f.first -= i * f.second; if (f > neg.back()) neg.push_back(f); } reverse(funcs.begin(), funcs.end()); for (auto f : funcs) { f.first += i * f.second; if (pos.empty() || f > pos.back()) pos.push_back(f); } reverse(pos.begin(), pos.end()); if (pos.back().second < mx) pos.emplace_back(-1 * mx * i, mx); funcs.clear(); int last = a[i].back(); for (int first : a[i]) { auto x = *lower_bound(pos.begin(), pos.end(), make_pair(0, first), cmp); auto y = *--upper_bound(neg.begin(), neg.end(), make_pair(0, first), cmp); funcs.emplace_back(max(x.first - i * first, y.first + i * first), last); last = first; } } auto ans = *max_element(funcs.begin(), funcs.end()); printf("%lld\n", ans.first); } assert(totalSum <= MX); return 0; }