import java.util.*;
import java.io.*;
public class main
{
    public static void main (String[] args)
    {
    	Scanner my = new Scanner(System.in);
    	int t = my.nextInt();
    	while(t>0) {
    	    int m;
    		int n = my.nextInt();
        	if(n<30) {
        		System.out.println("NO");
        	}
        	else {
        		System.out.println("YES");
        		if(n==36||n==44||n==40)
        		{
        			m = n-31;
        			System.out.println("6 10 15 " + m);
        		}
        		else {
        			m = n-30;
        			System.out.println("6 10 14 " + m);
        		}
        	}
        	t--;
    	}

    }

}


import java.util.*;
import java.io.*;
public class main
{
    public static void main (String[] args)
    {
    	Scanner my = new Scanner(System.in);
    	int t = my.nextInt();
    	while(t>0) {
    		int n = my.nextInt();
        	if(n<30) {
        		System.out.println("NO");
        	}
        	else {
        		System.out.println("YES");
        		if(n==36||n==44||n==40)
        		{
        			int m = n-31;
        			System.out.println(6 + " " + 10 + " " + 15 + " " + m);
        		}
        		else {
        			int m = n-30;
        			System.out.println(6 + " " + 10 + " " + 14 + " " + m);
        		}
        	}
        	t--;
    	}

    }

}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String args[] ) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        int x=0;
        while(t>0){
            int n=sc.nextInt();
            if(n>30){
                if((n-30)!=6 && (n-30)!=10 && (n-30)!=14){
                    System.out.println("6 10 14 "+(n-30));
                }
            }
            else
                System.out.println("NO");
            t--;
        }
    }

}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String args[] ) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t>0){
            int n=sc.nextInt();
            if(n>30){
                if((n-30)!=6 && (n-30)!=10 && (n-30)!=14){
                    System.out.println("YES");
                    System.out.println("6 10 14 "+(n-30));
                }
                else if((n-31)!=6 && (n-31)!=10 && (n-31)!=15){
                    System.out.println("YES");
                    System.out.println("6 10 15 "+(n-31));
                }
                else if((n-35)!=6 && (n-35)!=14 && (n-35)!=15){
                    System.out.println("YES");
                    System.out.println("6 14 15 "+(n-35));
                }
                else if((n-39)!=10 && (n-39)!=14 && (n-39)!=15){
                    System.out.println("YES");
                    System.out.println("10 14 15 "+(n-39));
                }
                else
                    System.out.println("NO");
            }
            else
                System.out.println("NO");
            t--;
        }
    }

}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String args[] ) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t>0){
            int n=sc.nextInt();
            if(n>30){
                if((n-30)!=6 && (n-30)!=10 && (n-30)!=14){
                    System.out.println("6 10 14 "+(n-30));
                }
            }
            else
                System.out.println("NO");
            t--;
        }
    }

}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String args[] ) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t>0){
            int n=sc.nextInt();
            if(n>30){
                if((n-30)!=6 && (n-30)!=10 && (n-30)!=14){
                    System.out.println("YES");
                    System.out.println("6 10 14 "+(n-30));
                }
            }
            else
                System.out.println("NO");
            t--;
        }
    }

}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String args[] ) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t>0){
            int n=sc.nextInt();
            if(n>30){
                System.out.println("YES");
                System.out.println("6 10 14"+" "+(n-30));
            }
            else
                System.out.println("NO");
            t--;
        }
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Integer.*;
//import static java.lang.Long.*;

public class D3 {

	public static void main(String[] args) throws IOException{

		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

		int t=1;
		int N=1000001;
//		int t=parseInt(in.readLine());
		while(t-->0){
			int n=parseInt(in.readLine());
			int freq[]=new int[N+1];
			ArrayList<Integer> left = new ArrayList<>();
			int flag[]=new int[n]; int fcount=0;
			for(int i=0;i<n;i++) {
				String ss[]=in.readLine().split(" ");
				int len=parseInt(ss[0]);
				int arr[]=new int[len];
				for(int j=0;j<len;j++)
					arr[j]=parseInt(ss[j+1]);
				int min=arr[0]; int max=arr[0];
				for(int j=0;j<len;j++) {
					if(arr[j]<min) {
						min=arr[j];
					}
					if(arr[j]>min)
						flag[i]=1;
					if(arr[j]>max) {
						max=arr[j];
					}
				}
				if(flag[i]!=1) {
					left.add(min);
					freq[max]++;
				}
				else
					fcount++;
			}
			TreeMap<Integer,Integer> tmap=new TreeMap<>();
			for(int i=N-1;i>=0;i--) {
				freq[i]+=freq[i+1];
				tmap.put(i,freq[i]);
			}
			long ans=0; ans+=(fcount*(2*n-1));
			for(int i=0;i<left.size();i++) {
				Object find=tmap.higherKey(left.get(i));
				if(find!=null) {
					int uz=tmap.get((int)find);
					ans+=uz;
				}
			}
			if(fcount>1)
				ans-=fcount;

			System.out.println(ans);
		}
	}
}


import java.io.*;
import java.util.*;
import static java.lang.Integer.*;
//import static java.lang.Long.*;

public class D3 {

	public static void main(String[] args) throws IOException{

		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

		int t=1;
		int N=1000001;
//		int t=parseInt(in.readLine());
		while(t-->0){
			int n=parseInt(in.readLine());
			int freq[]=new int[N+1];
			ArrayList<Integer> left = new ArrayList<>();
			int flag[]=new int[n];
			for(int i=0;i<n;i++) {
				String ss[]=in.readLine().split(" ");
				int len=parseInt(ss[0]);
				int arr[]=new int[len];
				for(int j=0;j<len;j++)
					arr[j]=parseInt(ss[j+1]);
				int min=arr[0]; int max=arr[0];
				for(int j=0;j<len;j++) {
					if(arr[j]>min)
						flag[i]=1;
					if(arr[j]<min) {
						min=arr[j];
					}
					if(arr[j]>max) {
						max=arr[j];
					}
				}
				if(flag[i]!=1) {
					left.add(min);
					freq[max]++;
				}
			}
			TreeMap<Integer,Integer> tmap=new TreeMap<>();
			tmap.put(0,freq[0]);
			for(int i=1;i<=N;i++) {
				freq[i]+=freq[i-1];
				tmap.put(i,freq[i]);
			}
			long ans=0;
			for(int i=0;i<left.size();i++) {
				Object find=tmap.floorKey(left.get(i));
				if(find!=null) {
					int uz=tmap.get((int)find);
					ans+=uz;
				}
			}
			long nn=n;
			ans=nn*nn-ans;
			System.out.println(ans);
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class ProblemB {
	public static void main(String[] args) throws IOException {
		InputStream in = System.in;
		InputReader scan = new InputReader(in);
		int n = scan.nextInt();
		int[] minSeq = new int[n];
		int[] maxSeq = new int[n];
		boolean[] ascent = new boolean[n];
		for(int i=0;i<n;i++) {
			int l = scan.nextInt();
			for(int j=0;j<l;j++) {
				int num = scan.nextInt();
				if(j==0) {
					minSeq[i] = num;
					maxSeq[i] = num;
				} else {
					if(num>minSeq[i]) ascent[i] = true;
					minSeq[i] = Math.min(num, minSeq[i]);
					maxSeq[i] = Math.max(num, maxSeq[i]);
				}
			}
		}
		int noOfAscent = 0;
		int noOfNonAscent = 0;
		ArrayList<Integer> nonAscArrMax = new ArrayList<>();
		for(int i=0;i<n;i++) {
			if(ascent[i]) noOfAscent++;
			else {
				noOfNonAscent++;
				nonAscArrMax.add(maxSeq[i]);
			}
		}
		Collections.sort(nonAscArrMax);
		long result = 0L;
		for(int i=0;i<n;i++) {
			if(ascent[i]) result+=n;
			else {
				result+=noOfAscent;
				int firstGreaterIndex = binSearchFirstGreaterIndex(minSeq[i], nonAscArrMax);
				if(firstGreaterIndex!=-1) {
					result+=(noOfNonAscent-firstGreaterIndex);
				}
			}
		}
		System.out.println(result);
	}
	static int binSearchFirstGreaterIndex(int val,ArrayList<Integer> arr) {
		int first = 0;
		int last = arr.size()-1;
		int returnIndex = -1;
		while(first<=last) {
			int mid = (first+last)/2;
			if(val>=arr.get(mid)) {
				first = mid+1;
			} else {
				returnIndex = mid;
				last = mid-1;
			}
		}
		return returnIndex;
	}
	static class InputReader {
		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream), 32768);
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class ProblemC {
	public static void main(String[] args) throws IOException {
		InputStream in = System.in;
		InputReader scan = new InputReader(in);
		int n = scan.nextInt();
		int[] minSeq = new int[n];
		int[] maxSeq = new int[n];
		boolean[] ascent = new boolean[n];
		for(int i=0;i<n;i++) {
			int l = scan.nextInt();
			for(int j=0;j<l;j++) {
				int num = scan.nextInt();
				if(j==0) {
					minSeq[i] = num;
					maxSeq[i] = num;
				} else {
					if(num>minSeq[i]) ascent[i] = true;
					minSeq[i] = Math.min(num, minSeq[i]);
					maxSeq[i] = Math.max(num, maxSeq[i]);
				}
			}
		}
		int noOfAscent = 0;
		int noOfNonAscent = 0;
		ArrayList<Integer> nonAscArrMax = new ArrayList<>();
		for(int i=0;i<n;i++) {
			if(ascent[i]) noOfAscent++;
			else {
				noOfNonAscent++;
				nonAscArrMax.add(maxSeq[i]);
			}
		}
		Collections.sort(nonAscArrMax);
		long result = 0L;
		for(int i=0;i<n;i++) {
			if(ascent[i]) result+=n;
			else {
				result+=noOfAscent;
				int firstGreaterIndex = binSearchLastIndexLesserOrEqual(minSeq[i], nonAscArrMax);
				if(firstGreaterIndex!=-1) {
					result+=(noOfNonAscent-firstGreaterIndex-1);
				}
			}
		}
		System.out.println(result);
	}
	static int binSearchLastIndexLesserOrEqual(int val,ArrayList<Integer> arr) {
		int first = 0;
		int last = arr.size()-1;
		int mid = (first+last)/2;
		int returnIndex = -1;
		while(first<=last) {
			mid = (first+last)/2;
			if(val>=arr.get(mid)) {
				returnIndex = Math.max(mid, returnIndex);
			}
			if(val<arr.get(mid)) {
				last = mid-1;
			} else {
				first = mid+1;
			}
		}
		return returnIndex;
	}
	static class InputReader {
		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream), 32768);
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class ProblemB {
	public static void main(String[] args) throws IOException {
		InputStream in = System.in;
		InputReader scan = new InputReader(in);
		int n = scan.nextInt();
		int[] minSeq = new int[n];
		int[] maxSeq = new int[n];
		boolean[] ascent = new boolean[n];
		for(int i=0;i<n;i++) {
			int l = scan.nextInt();
			for(int j=0;j<l;j++) {
				int num = scan.nextInt();
				if(j==0) {
					minSeq[i] = num;
					maxSeq[i] = num;
				} else {
					if(num>minSeq[i]) ascent[i] = true;
					minSeq[i] = Math.min(num, minSeq[i]);
					maxSeq[i] = Math.max(num, maxSeq[i]);
				}
			}
		}
		int noOfAscent = 0;
		int noOfNonAscent = 0;
		ArrayList<Integer> nonAscArrMax = new ArrayList<>();
		for(int i=0;i<n;i++) {
			if(ascent[i]) noOfAscent++;
			else {
				noOfNonAscent++;
				nonAscArrMax.add(maxSeq[i]);
			}
		}
		Collections.sort(nonAscArrMax);
		long result = 0L;
		for(int i=0;i<n;i++) {
			if(ascent[i]) result+=n;
			else {
				result+=noOfAscent;
				result+=(noOfNonAscent-binSearchLastIndexLesserOrEqual(minSeq[i], nonAscArrMax)-1);
			}
		}
		System.out.println(result);
	}
	static int binSearchLastIndexLesserOrEqual(int val,ArrayList<Integer> arr) {
		int first = 0;
		int last = arr.size()-1;
		int mid = (first+last)/2;
		int returnIndex = 0;
		while(first<=last) {
			mid = (first+last)/2;
			if(val>=arr.get(mid)) {
				returnIndex = Math.max(mid, returnIndex);
			}
			if(val<arr.get(mid)) {
				last = mid-1;
			} else {
				first = mid+1;
			}
		}
		return returnIndex;
	}
	static class InputReader {
		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream), 32768);
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author cunbidun
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1284C solver = new Task1284C();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1284C {
        private InputReader in;
        private OutputWriter out;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            this.in = in;
            this.out = out;
            int n = in.nextInt();
            int MOD = in.nextInt();
            int[] fac = new int[n + 1];
            fac[0] = 1;
            for (int i = 1; i <= n; i++) fac[i] = Op.mulMod(fac[i - 1], i, MOD);
            int ans = 0;
            for (int i = 1; i <= n; i++)
                ans = Op.addMod(ans, Op.mulMod(fac[n - i + 1], Op.mulMod(fac[i], n - i + 1, MOD), MOD), MOD);
            out.println(ans);
        }

    }

    static class OutputWriter {
        private final PrintWriter out;

        public OutputWriter(OutputStream outputStream) {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.out = new PrintWriter(writer);
        }

        public void close() {
            out.close();
        }

        public void println(int i) {
            out.println(i);
        }

    }

    static class InputReader extends InputStream {
        private InputStream stream;
        private byte[] buf = new byte[1 << 16];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        private static boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }

    static class Op {
        public static int addMod(int x, int y, int MOD) {
            return ((x + y) >= MOD ? x + y - MOD : x + y);
        }

        public static int mulMod(int x, int y, int MOD) {
            return (int) (((long) x * y) % MOD);
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author cunbidun
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1284B solver = new Task1284B();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1284B {
        private InputReader in;
        private OutputWriter out;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            this.in = in;
            this.out = out;
            int n = in.nextInt();
            long ans = 0;
            FTSum bit = new FTSum(1000005);
            int[] a = new int[n + 1];
            int[] b = new int[n + 1];
            int cnt = 0;
            for (int i = 1; i <= n; i++) {
                int k = in.nextInt();
                boolean d = false;
                int[] tmp = in.nextIntArray(k, 1);
                for (int j = 1; j <= k; j++) {
                    tmp[j] += 2;
                    if (j > 1 && tmp[j] > tmp[j - 1]) {
                        ans += n + n - 1;
                        cnt++;
                        d = true;
                        break;
                    }
                }
                if (d) continue;
                bit.update(tmp[k], 1);
                a[i] = tmp[1];
            }
            if (cnt != 0)
                ans -= (cnt - 1) * 2;
            for (int i = 1; i <= n; i++)
                if (a[i] != 0) {
                    ans += bit.getSum(a[i] - 1);
                }
            out.println(ans);
        }

    }

    static class OutputWriter {
        private final PrintWriter out;

        public OutputWriter(OutputStream outputStream) {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.out = new PrintWriter(writer);
        }

        public void close() {
            out.close();
        }

        public void println(long i) {
            out.println(i);
        }

    }

    static class InputReader extends InputStream {
        private InputStream stream;
        private byte[] buf = new byte[1 << 16];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int length, int stIndex) {
            int[] arr = new int[length + stIndex];
            for (int i = stIndex; i < stIndex + length; i++)
                arr[i] = nextInt();
            return arr;
        }

        private static boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }

    static class FTSum {
        private int n;
        private int[] sum;

        public FTSum(int n) {
            sum = new int[n + 1];
            this.n = n;
        }

        public void update(int pos, int val) {
            while (pos <= n) {
                sum[pos] += val;
                pos += pos & -pos;
            }
        }

        public int getSum(int pos) {
            int ans = 0;
            while (pos != 0) {
                ans += sum[pos];
                pos -= pos & -pos;
            }
            return ans;
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author cunbidun
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Task1284B solver = new Task1284B();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task1284B {
        private InputReader in;
        private OutputWriter out;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            this.in = in;
            this.out = out;
            int n = in.nextInt();
            FTSum bit = new FTSum(1000005);
            int[] a = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                int k = in.nextInt();
                boolean d = false;
                int[] tmp = in.nextIntArray(k, 1);
                for (int j = 1; j <= k; j++) {
                    tmp[j] += 2;
                    if (j > 1 && tmp[j] > tmp[j - 1]) {
                        d = true;
                        break;
                    }
                }
                if (d) continue;
                bit.update(tmp[1], 1);
                a[i] = tmp[k];
            }
            long res = 0;
            for (int i = 1; i <= n; i++)
                if (a[i] != 0) {
                    res += bit.getSum(a[i]);
                }
            out.println((long) n * n - res);
        }

    }

    static class InputReader extends InputStream {
        private InputStream stream;
        private byte[] buf = new byte[1 << 16];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int length, int stIndex) {
            int[] arr = new int[length + stIndex];
            for (int i = stIndex; i < stIndex + length; i++)
                arr[i] = nextInt();
            return arr;
        }

        private static boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }

    static class FTSum {
        private int n;
        private int[] sum;

        public FTSum(int n) {
            sum = new int[n + 1];
            this.n = n;
        }

        public void update(int pos, int val) {
            while (pos <= n) {
                sum[pos] += val;
                pos += pos & -pos;
            }
        }

        public int getSum(int pos) {
            int ans = 0;
            while (pos != 0) {
                ans += sum[pos];
                pos -= pos & -pos;
            }
            return ans;
        }

    }

    static class OutputWriter {
        private final PrintWriter out;

        public OutputWriter(OutputStream outputStream) {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.out = new PrintWriter(writer);
        }

        public void close() {
            out.close();
        }

        public void println(long i) {
            out.println(i);
        }

    }
}


import java.util.*;
public class Main
{
   public static void main(String args[])
   {
       Scanner sc=new Scanner(System.in);
       int t=sc.nextInt();
       boolean v[]=new boolean[t];
       int max[]=new int[1000002],min[]=new int[t];
       for(int l=0;l<t;l++)
       {
           int n=sc.nextInt();
           int mi=Integer.MAX_VALUE,ma=Integer.MIN_VALUE;
           for(int i=0;i<n;i++)
           {
               int s=sc.nextInt();
               mi=Math.min(mi,s);
               ma=Math.max(ma,s);
               if(mi<s)
                    v[l]=true;
           }
           if(!v[l])
           max[ma]+=1;
           min[l]=mi;
       }
       for(int i=1000000;i>=0;i--)
            max[i]+=max[i+1];
       long ans=0;
       int count=t;
       for(int i=0;i<t;i++)
       {
           if(v[i])
                ans+=2*(count--)-1;
           else
                ans+=max[min[i]+1];
       }
       System.out.println(ans);
    }
}


import java.util.*;
public class Main
{
   public static void main(String args[])
   {
       Scanner sc=new Scanner(System.in);
       int t=sc.nextInt();
       boolean v[]=new boolean[t];
       int max[]=new int[1000002],min[]=new int[t];
       for(int l=0;l<t;l++)
       {
           int n=sc.nextInt();
           int mi=Integer.MAX_VALUE,ma=Integer.MIN_VALUE;
           for(int i=0;i<n;i++)
           {
               int s=sc.nextInt();
               mi=Math.min(mi,s);
               ma=Math.max(ma,s);
               if(mi<s)
                    v[l]=true;
           }
           if(!v[l])
           max[ma]+=1;
           min[l]=mi;
       }
       for(int i=1000000;i>=0;i--)
            max[i]+=max[i+1];
       long ans=0;
       int count=0;
       for(int i=0;i<t;i++)
       {
           if(v[i])
                ans+=2*t-1+(count++)*0;
           else
                ans+=max[min[i]+1];
       }
       if(count>1)
       {
           ans-=2*(count-1);
       }
       System.out.println(ans);
    }
}


//package learning;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class NitsLocal {
    static ArrayList<String> s1;
    static boolean[] prime;
    static int n = (int)1e7;

     static void sieve() {
Arrays.fill(prime	, true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= n ; ++i) {
if(prime[i]) {
for(int k = i * i; k<= n ; k+=i) {
prime[k] = false;
}
}
}

}
    public static void main(String[] args) {
        InputReader sc = new InputReader(System.in);
        n *= 2;
           prime  = new boolean[n + 1];
           //sieve();
                prime[1] = false;

             /*
        int n = sc.ni();
        int k = sc.ni();
        int []vis = new int[n+1];
        int []a = new int[k];
        for(int i=0;i<k;i++)
        {
            a[i] = i+1;
        }
        int j = k+1;
        int []b = new int[n+1];
        for(int i=1;i<=n;i++)
        {
            b[i] = -1;
        }
        int y = n - k +1;
        int tr = 0;
        int y1 = k+1;
        while(y-- > 0)
        {
        System.out.print("? ");
        for(int i=0;i<k;i++)
        {
            System.out.print(a[i] + " ");
        }

        System.out.flush();
        int pos = sc.ni();
        int a1 = sc.ni();
        b[pos] = a1;

        for(int i=0;i<k;i++)
        {
            if(a[i] == pos)
            {
                a[i] = y1;
                y1++;
            }
        }
        }
        ArrayList<Integer> a2 = new ArrayList<>();
        if(y >= k)
        {

        int c = 0;
        int k1 = 0;
            for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {
                    c++;
                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }
                if(c==k)
                    break;
            }

            Collections.sort(a2);
            System.out.print("? ");
        for(int i=0;i<k;i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        System.out.flush();
        int pos = sc.ni();
        int a1 = sc.ni();
        int ans = -1;
        for(int i=0;i<a2.size();i++)
        {
            if(a2.get(i) == a1)
            {
                ans = i+1;
                break;
            }
        }
        System.out.println("!" + " " + ans);
           System.out.flush();
        }
        else
        {
            int k1 = 0;
            a = new int[k];
             for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {

                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }

            }
              for(int i=1;i<=n;i++)
            {
                if(b[i] == -1)
                {

                    a[k1] = i;

                    k1++;
                    if(k1==k)
                        break;
                }

            }
              int ans = -1;
              while(true)
              {
                   System.out.print("? ");
                     for(int i=0;i<k;i++)
                   {
                         System.out.print(a[i] + " ");
                  }
                   System.out.println();
                   System.out.flush();
                   int pos = sc.ni();
                   int a1 = sc.ni();
                   int f = 0;

                   if(b[pos] != -1)
                   {
                       Collections.sort(a2);
                       for(int i=0;i<a2.size();i++)
                       {
                           if(a2.get(i) == a1)
                           {
                               ans = i+1;
                               f = 1;
                               System.out.println("!" + " " + ans);
                               System.out.flush();
                               break;
                           }
                       }
                       if(f==1)
                           break;
                   }
                   else
                   {
                       b[pos] = a1;
                        a = new int[k];
                        a2.add(a1);
             for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {

                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }

            }
              for(int i=1;i<=n;i++)
            {
                if(b[i] == -1)
                {

                    a[k1] = i;

                    k1++;
                    if(k1==k)
                        break;
                }

            }

                   }
              }
        }
          */

                 int n = sc.ni();
                 ArrayList<Integer> []a1 = new ArrayList[n];
                 for(int i=0;i<n;i++)
                 {
                     a1[i] = new ArrayList<>();
                 }
                 for(int i=0;i<n;i++)
                 {
                     int q = sc.ni();
                     while(q-- > 0)
                     {
                         int a = sc.ni();
                         a1[i].add(a);

                     }
                 }
                 int []vis = new int[n];
                 long ans = 0;
                 int s1 = 0;
                 for(int i=0;i<n;i++)
                 {
                     if(a1[i].size() == 1)
                     {
                         vis[i] = 1;
                     }
                     else
                     {
                         s1++;
                         int f = 0;
                         for(int j=1;j<a1[i].size();j++)
                         {
                             if(a1[i].get(j) <= a1[i].get(j-1))
                             {

                             }
                             else
                             {
                                 f = 1;
                                 break;
                             }
                         }
                         if(f==0)
                             vis[i] = 2;

                     }
                 }
                 int c = 0;
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] == 0)
                     {
                         ans += (((long) 2* (long)(n-1-c)));
                         c++;
                     }
                 }
                 ans += (long) s1;

                   ArrayList<Integer> max = new ArrayList<>();
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] != 0)
                     {
                         int g = a1[i].size()-1;

                         max.add(a1[i].get(0));
                     }
                 }

                 Collections.sort(max);

                //w.println(ans);
                //w.println(ans);
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] != 0)
                     {
                         int g = a1[i].size()-1;
                       int y = upperBound(max,0,max.size(),a1[i].get(g));
                        int g1 = Collections.binarySearch(max, a1[i].get(0));

                       int req = max.size()-y;
                       if(vis[i]==2)
                       {
                           req--;
                          // w.println("*00");
                       }

                       ans += (long) req;

                       //w.println(y);

                     }
                 }

                 w.println(ans);
       w.close();

    }
     static int upperBound(ArrayList<Integer> a, int low, int high, int element){
    while(low < high){
        int middle = low + (high - low)/2;
        if(a.get(middle) > element)
            high = middle;
        else
            low = middle + 1;
    }
    return low;
}
   static long func(long t,long e,long h,long a, long b)
   {
       if(e*a >= t)
           return t/a;
       else
       {
           return e + Math.min(h,(t-e*a)/b);
       }
   }

    public static int upperBound(int []arr,int n,int num)
    {
        int l = 0;
        int r = n;
        while(l < r)
        {
            int mid = (l+r)/2;
            if(num >= arr[mid])
            {
                l = mid +1;
            }
            else
                r = mid;
        }
        return l;
    }
    public static int countSetBits(int number){
        int count = 0;
        while(number>0){
            ++count;
            number &= number-1;
        }
        return count;
    }

    static HashSet<Integer> fac;
    public static void primeFactors(int n)
    {
        // Print the number of 2s that divide n
        int t = 0;
        while (n%2==0)
        {
            fac.add(2);
            n /= 2;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (int i = 3; i*i <= n; i+= 2)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
                fac.add(i);
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            fac.add(n);
    }
     static long modexp(long x,long n,long M)
{
    long power = n;
    long result=1;
    x = x%M;
    while(power>0)
    {
        if(power % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        power = power/2;
    }
    return result;
}
      static long modInverse(long A,long M)
{
    return modexp(A,M-2,M);
}
    static long gcd(long a,long b)
    {
        if(a==0)
            return b;
        else
            return gcd(b%a,a);
    }
    static class Temp{
        int a;
        int b;
        int c;
        int d;

        Temp(int a,int b,int c,int d)
        {
            this.a = a;
            this.b = b;
            this.c  =c;
            this.d = d;
            //this.d = d;
        }
    }

   static long sum1(int t1,int t2,int x,int []t)
   {
       int mid = (t2-t1+1)/2;
  if(t1==t2)
      return 0;

   else
   return sum1(t1,mid-1,x,t) + sum1(mid,t2,x,t);

   }

    static String replace(String s,int a,int n)
    {
        char []c = s.toCharArray();
        for(int i=1;i<n;i+=2)
        {
            int num = (int) (c[i] - 48);
            num += a;
            num%=10;
            c[i] = (char) (num+48);
        }
        return new String(c);
    }
    static String move(String s,int h,int n)
    {
        h%=n;
        char []c = s.toCharArray();
        char []temp = new char[n];
        for(int i=0;i<n;i++)
        {
            temp[(i+h)%n] = c[i];
        }
        return new String(temp);
    }

     public static int ip(String s){
return Integer.parseInt(s);
}
     static class multipliers implements Comparator<Long>{

  public int compare(Long a,Long b) {
   if(a<b)
    return 1;
   else if(b<a)
    return -1;
   else
    return 0;
  }
 }
     static class multipliers1 implements Comparator<Student>{

  public int compare(Student a,Student b) {
   if(a.id<b.id)
    return -1;
   else if(b.id<a.id)
    return 1;
   else
   {
       if(a.y < b.y)
           return -1;
       else if(b.y<a.y)
           return 1;
       else
           return 0;

    //return 0;
   }
  }
 }
    // Java program to generate power set in
// lexicographic order.

      static class InputReader {

private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;

public InputReader(InputStream st) {
this.stream = st;
}

public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}

public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}

public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}

public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}

public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}

private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}

}

static PrintWriter w = new PrintWriter(System.out);
                  static class Student
    {
        int id;
        //int x;

        int y;

        //long z;

        Student(int id,int y)
        {
            this.id = id;
            //this.x = x;
            //this.s = s;
            this.y = y;

           // this.z = z;

        }

    }
}


//package learning;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class NitsLocal {
    static ArrayList<String> s1;
    static boolean[] prime;
    static int n = (int)1e7;

     static void sieve() {
Arrays.fill(prime	, true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= n ; ++i) {
if(prime[i]) {
for(int k = i * i; k<= n ; k+=i) {
prime[k] = false;
}
}
}

}
    public static void main(String[] args) {
        InputReader sc = new InputReader(System.in);
        n *= 2;
           prime  = new boolean[n + 1];
           //sieve();
                prime[1] = false;

             /*
        int n = sc.ni();
        int k = sc.ni();
        int []vis = new int[n+1];
        int []a = new int[k];
        for(int i=0;i<k;i++)
        {
            a[i] = i+1;
        }
        int j = k+1;
        int []b = new int[n+1];
        for(int i=1;i<=n;i++)
        {
            b[i] = -1;
        }
        int y = n - k +1;
        int tr = 0;
        int y1 = k+1;
        while(y-- > 0)
        {
        System.out.print("? ");
        for(int i=0;i<k;i++)
        {
            System.out.print(a[i] + " ");
        }

        System.out.flush();
        int pos = sc.ni();
        int a1 = sc.ni();
        b[pos] = a1;

        for(int i=0;i<k;i++)
        {
            if(a[i] == pos)
            {
                a[i] = y1;
                y1++;
            }
        }
        }
        ArrayList<Integer> a2 = new ArrayList<>();
        if(y >= k)
        {

        int c = 0;
        int k1 = 0;
            for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {
                    c++;
                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }
                if(c==k)
                    break;
            }

            Collections.sort(a2);
            System.out.print("? ");
        for(int i=0;i<k;i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        System.out.flush();
        int pos = sc.ni();
        int a1 = sc.ni();
        int ans = -1;
        for(int i=0;i<a2.size();i++)
        {
            if(a2.get(i) == a1)
            {
                ans = i+1;
                break;
            }
        }
        System.out.println("!" + " " + ans);
           System.out.flush();
        }
        else
        {
            int k1 = 0;
            a = new int[k];
             for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {

                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }

            }
              for(int i=1;i<=n;i++)
            {
                if(b[i] == -1)
                {

                    a[k1] = i;

                    k1++;
                    if(k1==k)
                        break;
                }

            }
              int ans = -1;
              while(true)
              {
                   System.out.print("? ");
                     for(int i=0;i<k;i++)
                   {
                         System.out.print(a[i] + " ");
                  }
                   System.out.println();
                   System.out.flush();
                   int pos = sc.ni();
                   int a1 = sc.ni();
                   int f = 0;

                   if(b[pos] != -1)
                   {
                       Collections.sort(a2);
                       for(int i=0;i<a2.size();i++)
                       {
                           if(a2.get(i) == a1)
                           {
                               ans = i+1;
                               f = 1;
                               System.out.println("!" + " " + ans);
                               System.out.flush();
                               break;
                           }
                       }
                       if(f==1)
                           break;
                   }
                   else
                   {
                       b[pos] = a1;
                        a = new int[k];
                        a2.add(a1);
             for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {

                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }

            }
              for(int i=1;i<=n;i++)
            {
                if(b[i] == -1)
                {

                    a[k1] = i;

                    k1++;
                    if(k1==k)
                        break;
                }

            }

                   }
              }
        }
          */

                 int n = sc.ni();
                 ArrayList<Integer> []a1 = new ArrayList[n];
                 for(int i=0;i<n;i++)
                 {
                     a1[i] = new ArrayList<>();
                 }
                 for(int i=0;i<n;i++)
                 {
                     int q = sc.ni();
                     while(q-- > 0)
                     {
                         int a = sc.ni();
                         a1[i].add(a);

                     }
                 }
                 int []vis = new int[n];
                 long ans = 0;
                 int s1 = 0;
                 for(int i=0;i<n;i++)
                 {
                     if(a1[i].size() == 1)
                     {
                         vis[i] = 1;
                     }
                     else
                     {
                         s1++;
                         int f = 0;
                         for(int j=1;j<a1[i].size();j++)
                         {
                             if(a1[i].get(j) <= a1[i].get(j-1))
                             {

                             }
                             else
                             {
                                 f = 1;
                                 break;
                             }
                         }
                         if(f==0)
                             vis[i] = 2;

                     }
                 }
                 int c = 0;
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] == 0)
                     {
                         ans += (((long) 2* (long)(n-1-c)));
                         c++;
                     }
                 }
                 ans += (long) s1;
                 ArrayList<Integer> min = new ArrayList<>();
                   ArrayList<Integer> max = new ArrayList<>();
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] != 0)
                     {
                         int g = a1[i].size()-1;
                         min.add(a1[i].get(g));
                         max.add(a1[i].get(0));
                     }
                 }
                 Collections.sort(min);
                 Collections.sort(max);

                //w.println(ans);
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] != 0)
                     {
                         int g = a1[i].size()-1;
                       int y = upperBound(max,0,max.size(),a1[i].get(g));
                        int g1 = Collections.binarySearch(max, a1[i].get(0));

                       int req = max.size()-y;
                       if(g1 >= y)
                           req--;
                       ans += (long) req;

                       //w.println(y);

                     }
                 }

                 w.println(ans);
       w.close();

    }
     static int upperBound(ArrayList<Integer> a, int low, int high, int element){
    while(low < high){
        int middle = low + (high - low)/2;
        if(a.get(middle) > element)
            high = middle;
        else
            low = middle + 1;
    }
    return low;
}
   static long func(long t,long e,long h,long a, long b)
   {
       if(e*a >= t)
           return t/a;
       else
       {
           return e + Math.min(h,(t-e*a)/b);
       }
   }

    public static int upperBound(int []arr,int n,int num)
    {
        int l = 0;
        int r = n;
        while(l < r)
        {
            int mid = (l+r)/2;
            if(num >= arr[mid])
            {
                l = mid +1;
            }
            else
                r = mid;
        }
        return l;
    }
    public static int countSetBits(int number){
        int count = 0;
        while(number>0){
            ++count;
            number &= number-1;
        }
        return count;
    }

    static HashSet<Integer> fac;
    public static void primeFactors(int n)
    {
        // Print the number of 2s that divide n
        int t = 0;
        while (n%2==0)
        {
            fac.add(2);
            n /= 2;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (int i = 3; i*i <= n; i+= 2)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
                fac.add(i);
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            fac.add(n);
    }
     static long modexp(long x,long n,long M)
{
    long power = n;
    long result=1;
    x = x%M;
    while(power>0)
    {
        if(power % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        power = power/2;
    }
    return result;
}
      static long modInverse(long A,long M)
{
    return modexp(A,M-2,M);
}
    static long gcd(long a,long b)
    {
        if(a==0)
            return b;
        else
            return gcd(b%a,a);
    }
    static class Temp{
        int a;
        int b;
        int c;
        int d;

        Temp(int a,int b,int c,int d)
        {
            this.a = a;
            this.b = b;
            this.c  =c;
            this.d = d;
            //this.d = d;
        }
    }

   static long sum1(int t1,int t2,int x,int []t)
   {
       int mid = (t2-t1+1)/2;
  if(t1==t2)
      return 0;

   else
   return sum1(t1,mid-1,x,t) + sum1(mid,t2,x,t);

   }

    static String replace(String s,int a,int n)
    {
        char []c = s.toCharArray();
        for(int i=1;i<n;i+=2)
        {
            int num = (int) (c[i] - 48);
            num += a;
            num%=10;
            c[i] = (char) (num+48);
        }
        return new String(c);
    }
    static String move(String s,int h,int n)
    {
        h%=n;
        char []c = s.toCharArray();
        char []temp = new char[n];
        for(int i=0;i<n;i++)
        {
            temp[(i+h)%n] = c[i];
        }
        return new String(temp);
    }

     public static int ip(String s){
return Integer.parseInt(s);
}
     static class multipliers implements Comparator<Long>{

  public int compare(Long a,Long b) {
   if(a<b)
    return 1;
   else if(b<a)
    return -1;
   else
    return 0;
  }
 }
     static class multipliers1 implements Comparator<Student>{

  public int compare(Student a,Student b) {
   if(a.id<b.id)
    return -1;
   else if(b.id<a.id)
    return 1;
   else
   {
       if(a.y < b.y)
           return -1;
       else if(b.y<a.y)
           return 1;
       else
           return 0;

    //return 0;
   }
  }
 }
    // Java program to generate power set in
// lexicographic order.

      static class InputReader {

private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;

public InputReader(InputStream st) {
this.stream = st;
}

public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}

public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}

public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}

public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}

public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}

private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}

}

static PrintWriter w = new PrintWriter(System.out);
                  static class Student
    {
        int id;
        //int x;

        int y;

        //long z;

        Student(int id,int y)
        {
            this.id = id;
            //this.x = x;
            //this.s = s;
            this.y = y;

           // this.z = z;

        }

    }
}


//package learning;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class NitsLocal {
    static ArrayList<String> s1;
    static boolean[] prime;
    static int n = (int)1e7;

     static void sieve() {
Arrays.fill(prime	, true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= n ; ++i) {
if(prime[i]) {
for(int k = i * i; k<= n ; k+=i) {
prime[k] = false;
}
}
}

}
    public static void main(String[] args) {
        InputReader sc = new InputReader(System.in);
        n *= 2;
           prime  = new boolean[n + 1];
           //sieve();
                prime[1] = false;

             /*
        int n = sc.ni();
        int k = sc.ni();
        int []vis = new int[n+1];
        int []a = new int[k];
        for(int i=0;i<k;i++)
        {
            a[i] = i+1;
        }
        int j = k+1;
        int []b = new int[n+1];
        for(int i=1;i<=n;i++)
        {
            b[i] = -1;
        }
        int y = n - k +1;
        int tr = 0;
        int y1 = k+1;
        while(y-- > 0)
        {
        System.out.print("? ");
        for(int i=0;i<k;i++)
        {
            System.out.print(a[i] + " ");
        }

        System.out.flush();
        int pos = sc.ni();
        int a1 = sc.ni();
        b[pos] = a1;

        for(int i=0;i<k;i++)
        {
            if(a[i] == pos)
            {
                a[i] = y1;
                y1++;
            }
        }
        }
        ArrayList<Integer> a2 = new ArrayList<>();
        if(y >= k)
        {

        int c = 0;
        int k1 = 0;
            for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {
                    c++;
                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }
                if(c==k)
                    break;
            }

            Collections.sort(a2);
            System.out.print("? ");
        for(int i=0;i<k;i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        System.out.flush();
        int pos = sc.ni();
        int a1 = sc.ni();
        int ans = -1;
        for(int i=0;i<a2.size();i++)
        {
            if(a2.get(i) == a1)
            {
                ans = i+1;
                break;
            }
        }
        System.out.println("!" + " " + ans);
           System.out.flush();
        }
        else
        {
            int k1 = 0;
            a = new int[k];
             for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {

                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }

            }
              for(int i=1;i<=n;i++)
            {
                if(b[i] == -1)
                {

                    a[k1] = i;

                    k1++;
                    if(k1==k)
                        break;
                }

            }
              int ans = -1;
              while(true)
              {
                   System.out.print("? ");
                     for(int i=0;i<k;i++)
                   {
                         System.out.print(a[i] + " ");
                  }
                   System.out.println();
                   System.out.flush();
                   int pos = sc.ni();
                   int a1 = sc.ni();
                   int f = 0;

                   if(b[pos] != -1)
                   {
                       Collections.sort(a2);
                       for(int i=0;i<a2.size();i++)
                       {
                           if(a2.get(i) == a1)
                           {
                               ans = i+1;
                               f = 1;
                               System.out.println("!" + " " + ans);
                               System.out.flush();
                               break;
                           }
                       }
                       if(f==1)
                           break;
                   }
                   else
                   {
                       b[pos] = a1;
                        a = new int[k];
                        a2.add(a1);
             for(int i=1;i<=n;i++)
            {
                if(b[i] != -1)
                {

                    a[k1] = i;
                    a2.add(b[i]);
                    k1++;
                }

            }
              for(int i=1;i<=n;i++)
            {
                if(b[i] == -1)
                {

                    a[k1] = i;

                    k1++;
                    if(k1==k)
                        break;
                }

            }

                   }
              }
        }
          */

                 int n = sc.ni();
                 ArrayList<Integer> []a1 = new ArrayList[n];
                 for(int i=0;i<n;i++)
                 {
                     a1[i] = new ArrayList<>();
                 }
                 for(int i=0;i<n;i++)
                 {
                     int q = sc.ni();
                     while(q-- > 0)
                     {
                         int a = sc.ni();
                         a1[i].add(a);

                     }
                 }
                 int []vis = new int[n];
                 long ans = 0;
                 int s1 = 0;
                 for(int i=0;i<n;i++)
                 {
                     if(a1[i].size() == 1)
                     {
                         vis[i] = 1;
                     }
                     else
                     {
                         s1++;
                         int f = 0;
                         for(int j=1;j<a1[i].size();j++)
                         {
                             if(a1[i].get(j) <= a1[i].get(j-1))
                             {

                             }
                             else
                             {
                                 f = 1;
                                 break;
                             }
                         }
                         if(f==0)
                             vis[i] = 2;

                     }
                 }
                 int c = 0;
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] == 0)
                     {
                         ans += (((long) 2* (long)(n-1-c)));
                         c++;
                     }
                 }
                 ans += (long) s1;

                   ArrayList<Integer> max = new ArrayList<>();
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] != 0)
                     {
                         int g = a1[i].size()-1;

                         max.add(a1[i].get(0));
                     }
                 }

                 Collections.sort(max);

                //w.println(ans);
                 for(int i=0;i<n;i++)
                 {
                     if(vis[i] != 0)
                     {
                         int g = a1[i].size()-1;
                       int y = upperBound(max,0,max.size()-1,a1[i].get(g));
                        int g1 = Collections.binarySearch(max, a1[i].get(0));

                       int req = max.size()-y;
                       if(g1 >= y)
                           req--;
                       if(req < 0)
                           req = 0;
                       ans += (long) req;

                       //w.println(y);

                     }
                 }

                 w.println(ans);
       w.close();

    }
     static int upperBound(ArrayList<Integer> a, int low, int high, int element){
    while(low < high){
        int middle = low + (high - low)/2;
        if(a.get(middle) > element)
            high = middle;
        else
            low = middle + 1;
    }
    return low;
}
   static long func(long t,long e,long h,long a, long b)
   {
       if(e*a >= t)
           return t/a;
       else
       {
           return e + Math.min(h,(t-e*a)/b);
       }
   }

    public static int upperBound(int []arr,int n,int num)
    {
        int l = 0;
        int r = n;
        while(l < r)
        {
            int mid = (l+r)/2;
            if(num >= arr[mid])
            {
                l = mid +1;
            }
            else
                r = mid;
        }
        return l;
    }
    public static int countSetBits(int number){
        int count = 0;
        while(number>0){
            ++count;
            number &= number-1;
        }
        return count;
    }

    static HashSet<Integer> fac;
    public static void primeFactors(int n)
    {
        // Print the number of 2s that divide n
        int t = 0;
        while (n%2==0)
        {
            fac.add(2);
            n /= 2;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (int i = 3; i*i <= n; i+= 2)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
                fac.add(i);
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            fac.add(n);
    }
     static long modexp(long x,long n,long M)
{
    long power = n;
    long result=1;
    x = x%M;
    while(power>0)
    {
        if(power % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        power = power/2;
    }
    return result;
}
      static long modInverse(long A,long M)
{
    return modexp(A,M-2,M);
}
    static long gcd(long a,long b)
    {
        if(a==0)
            return b;
        else
            return gcd(b%a,a);
    }
    static class Temp{
        int a;
        int b;
        int c;
        int d;

        Temp(int a,int b,int c,int d)
        {
            this.a = a;
            this.b = b;
            this.c  =c;
            this.d = d;
            //this.d = d;
        }
    }

   static long sum1(int t1,int t2,int x,int []t)
   {
       int mid = (t2-t1+1)/2;
  if(t1==t2)
      return 0;

   else
   return sum1(t1,mid-1,x,t) + sum1(mid,t2,x,t);

   }

    static String replace(String s,int a,int n)
    {
        char []c = s.toCharArray();
        for(int i=1;i<n;i+=2)
        {
            int num = (int) (c[i] - 48);
            num += a;
            num%=10;
            c[i] = (char) (num+48);
        }
        return new String(c);
    }
    static String move(String s,int h,int n)
    {
        h%=n;
        char []c = s.toCharArray();
        char []temp = new char[n];
        for(int i=0;i<n;i++)
        {
            temp[(i+h)%n] = c[i];
        }
        return new String(temp);
    }

     public static int ip(String s){
return Integer.parseInt(s);
}
     static class multipliers implements Comparator<Long>{

  public int compare(Long a,Long b) {
   if(a<b)
    return 1;
   else if(b<a)
    return -1;
   else
    return 0;
  }
 }
     static class multipliers1 implements Comparator<Student>{

  public int compare(Student a,Student b) {
   if(a.id<b.id)
    return -1;
   else if(b.id<a.id)
    return 1;
   else
   {
       if(a.y < b.y)
           return -1;
       else if(b.y<a.y)
           return 1;
       else
           return 0;

    //return 0;
   }
  }
 }
    // Java program to generate power set in
// lexicographic order.

      static class InputReader {

private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;

public InputReader(InputStream st) {
this.stream = st;
}

public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}

public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}

public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}

public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}

public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}

public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}

private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}

}

static PrintWriter w = new PrintWriter(System.out);
                  static class Student
    {
        int id;
        //int x;

        int y;

        //long z;

        Student(int id,int y)
        {
            this.id = id;
            //this.x = x;
            //this.s = s;
            this.y = y;

           // this.z = z;

        }

    }
}


import java.io.*;
import java.util.StringTokenizer;

public class Solution {
    private static boolean doLocalTest = System.getSecurityManager() == null;
    private Scanner sc = new Scanner(System.in);
    private PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

    public static void main(String[] args) {
        long executionTime = 0;
        if (doLocalTest) {
            executionTime = System.currentTimeMillis();
            try {
                System.setIn((new FileInputStream("in")));
            } catch (FileNotFoundException e) {
                doLocalTest = false;
            }
        }
        Solution solution = new Solution();
        solution.solve();
        if (doLocalTest) {
            solution.out.println("======== [ End of Output] ========");
            solution.out.println("> Time Spent: " + (System.currentTimeMillis() - executionTime) + " ms");
        }
        solution.out.flush();
    }

    private void solve() {
        int n = sc.nextInt();
        int[] begin = new int[1000007], end = new int[1000007];
        long ascent = 0;
        for (int index = 0; index < n; index++) {
            int l = sc.nextInt();
            int[] s = new int[l];
            int min = sc.nextInt(), max = min;
            l--;
            boolean flag = false;
            while (l-- > 0) {
                int next = sc.nextInt();
                if (!flag) {
                    if (next > min) {
                        flag = true;
                    } else {
                        min = next;
                    }
                }
            }
            if (flag) {
                ascent++;
            } else {
                begin[min]++;
                end[max]++;
            }
        }
        long counter = 0;
        counter += ascent * (n - 1) * 2 + ascent - ascent * (ascent - 1);
        long current = 0;
        for (int index = 0; index <= 1000000; index++) {
            counter += end[index] * current;
            current += begin[index];
        }
        out.println(counter);
    }

}

class Scanner {
    private BufferedReader bufferedReader;
    private StringTokenizer stringTokenizer;

    Scanner(InputStream in) {
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        stringTokenizer = new StringTokenizer("");
    }

    String nextLine() {
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            throw new IOError(e);
        }
    }

    boolean hasNext() {
        while (!stringTokenizer.hasMoreTokens()) {
            String s = nextLine();
            if (s == null) {
                return false;
            }
            stringTokenizer = new StringTokenizer(s);
        }
        return true;
    }

    String next() {
        hasNext();
        return stringTokenizer.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }
}


import java.io.*;
import java.util.StringTokenizer;

public class Solution {
    private static boolean doLocalTest = System.getSecurityManager() == null;
    private Scanner sc = new Scanner(System.in);
    private PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

    public static void main(String[] args) {
        long executionTime = 0;
        if (doLocalTest) {
            executionTime = System.currentTimeMillis();
            try {
                System.setIn((new FileInputStream("in")));
            } catch (FileNotFoundException e) {
                doLocalTest = false;
            }
        }
        Solution solution = new Solution();
        solution.solve();
        if (doLocalTest) {
            solution.out.println("======== [ End of Output] ========");
            solution.out.println("> Time Spent: " + (System.currentTimeMillis() - executionTime) + " ms");
        }
        solution.out.flush();
    }

    private void solve() {
        int n = sc.nextInt();
        int[] begin = new int[100007], end = new int[100007];
        long ascent = 0;
        for (int index = 0; index < n; index++) {
            int l = sc.nextInt();
            int[] s = new int[l];
            int min = sc.nextInt(), max = min;
            l--;
            boolean flag = false;
            while (l-- > 0) {
                int next = sc.nextInt();
                if (!flag) {
                    if (next > min) {
                        flag = true;
                    } else {
                        min = next;
                    }
                }
            }
            if (flag) {
                ascent++;
            } else {
                begin[min]++;
                end[max]++;
            }
        }
        long counter = 0;
        counter += ascent * (n - 1) * 2 + ascent - ascent * (ascent - 1);
        long current = 0;
        for (
                int index = 0;
                index <= 100000; index++) {
            counter += end[index] * current;
            current += begin[index];
        }
        out.println(counter);
    }

}

class Scanner {
    private BufferedReader bufferedReader;
    private StringTokenizer stringTokenizer;

    Scanner(InputStream in) {
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        stringTokenizer = new StringTokenizer("");
    }

    String nextLine() {
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            throw new IOError(e);
        }
    }

    boolean hasNext() {
        while (!stringTokenizer.hasMoreTokens()) {
            String s = nextLine();
            if (s == null) {
                return false;
            }
            stringTokenizer = new StringTokenizer(s);
        }
        return true;
    }

    String next() {
        hasNext();
        return stringTokenizer.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }
}


import java.io.*;
import java.util.*;
public class B {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int n = sc.nextInt();
		long res = 0;
		int[] min = new int[n];
		int[] max = new int[n];
		int currn = n;
		for(int i = 0; i < n; i++) {
			int k = sc.nextInt();
			int cmax = -1, cmin = 1000001;
			for(int j = 0; j < k; j++) {
				int a = sc.nextInt();
				if(a > cmin) {
					cmax = -2;
					cmin = -2;
				}
				if(cmax > -2) {
					cmax = Integer.max(cmax, a);
					cmin = Integer.min(cmin, a);
				}
			}
			if(cmax == -2) {
				res += 2 * (long)currn - 1;
				currn--;
			}
			min[i] = cmin;
			max[i] = cmax;
		}
		ArrayList<Integer> mins = new ArrayList();
		ArrayList<Integer> maxs = new ArrayList();
		for(int k: min) if(k != -2) mins.add(k);
		for(int k: max) if(k != -2) maxs.add(k);
		Collections.sort(maxs);
		Collections.sort(mins);
		int i = 0, j = 0;
		while(i < currn) {
			while(j < currn && mins.get(i) >= maxs.get(j)) j++;
			res += (long)(currn-j);
			i++;
		}
		System.out.println(res);
	}
	static class FastScanner {
		public BufferedReader reader;
		public StringTokenizer tokenizer;
		public FastScanner() {
			reader = new BufferedReader(new InputStreamReader(System.in), 32768);
			tokenizer = null;
		}
		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		public String nextLine() {
			try {
				return reader.readLine();
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

}


import java.io.*;
import java.util.*;
public class B {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int n = sc.nextInt();
		long res = 0;
		int[] min = new int[n];
		int[] max = new int[n];
		int currn = n;
		for(int i = 0; i < n; i++) {
			int k = sc.nextInt();
			int cmax = -1, cmin = 1000001;
			for(int j = 0; j < k; j++) {
				int a = sc.nextInt();
				if(a > cmin) {
					cmax = -2;
					cmin = -2;
				}
				if(cmax > -2) {
					cmax = Integer.max(cmax, a);
					cmin = Integer.min(cmin, a);
				}
			}
			if(cmax == -2) {
				res += 2 * (long)currn - 1;
				currn--;
			}
			else {
				min[i] = cmin;
				max[i] = cmax;
			}
		}
		ArrayList<Integer> mins = new ArrayList();
		ArrayList<Integer> maxs = new ArrayList();
		for(int k: min) if(k != -2) mins.add(k);
		for(int k: max) if(k != -2) maxs.add(k);
		Collections.sort(maxs);
		Collections.sort(mins);
		int i = 0, j = 0;
		while(i < currn) {
			while(j < currn && mins.get(i) >= maxs.get(j)) j++;
			res += (long)(currn-j);
			i++;
		}
		System.out.println(res);
	}
	static class FastScanner {
		public BufferedReader reader;
		public StringTokenizer tokenizer;
		public FastScanner() {
			reader = new BufferedReader(new InputStreamReader(System.in), 32768);
			tokenizer = null;
		}
		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		public String nextLine() {
			try {
				return reader.readLine();
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

}


import java.io.*;
import java.util.*;
public class B {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int n = sc.nextInt();
		int res = 0;
		int[] min = new int[n];
		int[] max = new int[n];
		int currn = n;
		for(int i = 0; i < n; i++) {
			int k = sc.nextInt();
			int cmax = -1, cmin = 1000001;
			for(int j = 0; j < k; j++) {
				int a = sc.nextInt();
				if(a > cmin) {
					cmax = -2;
					cmin = -2;
				}
				if(cmax > -2) {
					cmax = Integer.max(cmax, a);
					cmin = Integer.min(cmin, a);
				}
			}
			if(cmax == -2) {
				res += 2 * currn - 1;
				currn--;
			}
			min[i] = cmin;
			max[i] = cmax;
		}
		ArrayList<Integer> mins = new ArrayList();
		ArrayList<Integer> maxs = new ArrayList();
		for(int k: min) if(k != -2) mins.add(k);
		for(int k: max) if(k != -2) maxs.add(k);
		Collections.sort(maxs);
		Collections.sort(mins);
		int i = 0, j = 0;
		while(i < currn) {
			while(j < currn && mins.get(i) >= maxs.get(j)) j++;
			if(j < currn && mins.get(i) < maxs.get(j)) res += (currn-j);
			i++;
		}
		System.out.println(res);
	}
	static class FastScanner {
		public BufferedReader reader;
		public StringTokenizer tokenizer;
		public FastScanner() {
			reader = new BufferedReader(new InputStreamReader(System.in), 32768);
			tokenizer = null;
		}
		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		public String nextLine() {
			try {
				return reader.readLine();
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

}


import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;

import static java.lang.Math.*;

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
                return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<27).start();
    }
    public void run() {

        InputReader sc = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n=sc.nextInt();

        int arr[][]=new int[n][2];

        boolean flag[]=new boolean[n];

        for(int i=0;i<n;i++)
        {
            int m=sc.nextInt();
            int a[]=new int[m];

            int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;

            for(int j=0;j<m;j++)
            {
                a[j]=sc.nextInt();
                min=Math.min(a[j],min);
                max=Math.max(a[j],max);

                if(!flag[i] && min!=a[j] && min<max)
                    flag[i]=true;
            }
            arr[i][0]=min;
            arr[i][1]=max;

        }

        long tot=0;

        for(int i=0;i<n;i++)
        {
            if(flag[i])
            {
                tot+=n;
                continue;
            }
            for(int j=0;j<n;j++)
            {
                if(arr[i][0]<arr[j][1] || flag[j])
                    tot++;
            }
        }

        out.println(tot);
        out.close();
    }
}


import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;

import static java.lang.Math.*;

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
                return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<27).start();
    }
    public void run() {

        InputReader sc = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n=sc.nextInt();

        int arr[][]=new int[n][2];

        boolean flag[]=new boolean[n];

        for(int i=0;i<n;i++)
        {
            int m=sc.nextInt();
            int a[]=new int[m];

            int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;
            boolean local=false;
            for(int j=0;j<m;j++)
            {
                if(local)
                {

                    String zzz=sc.next();
                    continue;
                }
                a[j]=sc.nextInt();

                min=Math.min(a[j],min);
                max=Math.max(a[j],max);

                if(!flag[i] && min!=a[j] && min<max)
                {
                    flag[i]=true;
                    local=true;

                }
            }
            arr[i][0]=min;
            arr[i][1]=max;

        }

        long tot=0;

        for(int i=0;i<n;i++)
        {
            if(flag[i])
            {
                tot+=n;
                continue;
            }
            for(int j=0;j<n;j++)
            {
                if(flag[j] || arr[i][0]<arr[j][1])
                    tot++;
            }
        }

        out.println(tot);
        out.close();
    }
}