#include <bits/stdc++.h>

using namespace std;

#define sz(x) ((int)x.size())

void solve()
{
   int N, S, Q;
   cin >> N >> S >> Q;
   vector<queue<int>> cargoes(N);
   int totalCargoes = 0;
   for (int i = 0; i < N; i++)
   {
      int q;
      cin >> q;
      totalCargoes += q;
      for (int j = 0; j < q; j++)
      {
         int c;
         cin >> c;
         cargoes[i].push(c - 1);
      }
   }

   stack<int> carrier;
   int station = 0, totalTime = 0;
   for (int cargoesDelivered = 0; cargoesDelivered < totalCargoes;)
   {
      while (!carrier.empty() && (carrier.top() == station || sz(cargoes[station]) < Q))
      {
         if (carrier.top() == station)
         {
            cargoesDelivered++;
         }
         else
         {
            cargoes[station].push(carrier.top());
         }
         carrier.pop();
         totalTime++;
      }
      while (!cargoes[station].empty() && sz(carrier) < S)
      {
         carrier.push(cargoes[station].front());
         cargoes[station].pop();
         totalTime++;
      }
      station = (station + 1) % N;
      if (cargoesDelivered < totalCargoes)
         totalTime += 2; // move to next station
   }

   cout << totalTime << endl;
}

int main()
{
   int t; cin >> t;
   while (t--) solve();
   return 0;
}