#include <bits/stdc++.h>
using namespace std;
bool isSorted(vector<long long> &v) {
  for (int i = 0; i < v.size() - 1; i++)
    if (v[i] > v[i + 1]) return false;
  return true;
}
bool cmp(pair<long, long> x, pair<long, long> y) {
  if (x.first == y.first) return x.second > y.second;
  return x.first < y.first;
}
void solve() {
  long long n, ans = -1;
  cin >> n;
  vector<pair<long, long> > v(n);
  for (long long i = 0; i < n; i++) {
    long long m;
    cin >> m;
    v[i] = {0, m};
    for (long long j = 0; j < m; j++) {
      long long tmp;
      cin >> tmp;
      v[i].first = max((long long)v[i].first, tmp + 1 - j);
    }
  }
  sort(v.begin(), v.end(), cmp);
  long long curHealth = -1;
  for (long long i = 0; i < n; i++) {
    if (curHealth == -1) {
      ans = v[i].first;
      curHealth = v[i].second + v[i].first;
    } else {
      if (curHealth < v[i].first) {
        ans += v[i].first - curHealth;
        curHealth = v[i].first;
      }
      curHealth += v[i].second;
    }
  }
  cout << ans << endl;
}
int main() {
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
