#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
#define N 1000005
using namespace std;
typedef long long ll;
const ll oo=900000000000000000LL;
struct tree {
int tag, ch[2];
ll data;
tree(): data(-oo), tag(rand()*rand()) { ch[0]=ch[1]=0; }
} mem[N];
int root=0, cnt=1, fa=-1;
bool rec, td;
inline int rot(const int T, const bool d) {
int x=mem[T].ch[d], y=mem[x].ch[!d]; //if (x==0) return T;
mem[T].ch[d]=y; mem[x].ch[!d]=T;
return x;
}
int ins(int T, ll d0) {
bool d;
if (!T) { mem[cnt].data=d0; return cnt++; }
mem[T].ch[d=(d0>=mem[T].data)]=ins(mem[T].ch[d], d0);
if (mem[mem[T].ch[d]].tag>mem[T].tag) T=rot(T, d);
return T;
}
int fin(int T, ll d0, int best, bool d) { //d==1 means find the nearest one less than it.
if (!T) return best;
if (d^(mem[T].data>d0)) best=T;
return fin(mem[T].ch[!(d^(best==T))],d0,best,d);
}
int del(int T, ll todel) {
int ret=T; bool d;
if (todel==mem[T].data) {
if (!(mem[T].ch[0]||mem[T].ch[1])) return 0;
ret=rot(T, d=(mem[mem[T].ch[0]].tag<mem[mem[T].ch[1]].tag));
mem[ret].ch[!d]=del(T,todel);
}
else mem[T].ch[d=todel>mem[T].data]=del(mem[T].ch[d],todel);
return ret;
}
inline ll mabs(ll x) {
return (x<0)?-x:x;
}
int main() {
int tt, f; ll fans=0; scanf("%d", &tt);
srand(223133); mem[0].tag=-0x7fffffff;
while (tt--) {
int k; scanf("%d", &k);
for (int i=0; i<k; ++i) {
ll x; scanf("%lld", &x); root=ins(root, x);
}
ll t1=mem[fin(root, oo, 0, 1)].data;
ll t2=mem[fin(root, -oo, 0, 0)].data;
fans+=(t1-t2);
root=del(root, t1); root=del(root, t2);
}
printf("%lld\n", fans);
return 0;
}