#include using namespace std; const int MX = 1000000; vector a[MX]; int main() { int T; ignore = scanf("%d", &T); while (T--) { int n; ignore = scanf("%d", &n); for (int i = 0, m; i < n; i++) { a[i].clear(); ignore = scanf("%d", &m); for (int j = 0, x; j < m; j++) { ignore = scanf("%d", &x); a[i].push_back(x); } } 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; } } __int128_t ans = (*max_element(funcs.begin(), funcs.end())).first; assert(ans < (__int128_t)1e19); printf("%lld\n", (long long)ans); } return 0; }