Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $m$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $1$ to $n$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.

However, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" — thinks Gawry — "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.

In how many ways he can do it? Two ways are called different if the remaining common part is different.


-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $1 \le m \le 10$) — the number of suspects and the number of asked neighbors.

Each of the next $m$ lines contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). It is guaranteed that these integers form a correct permutation (that is, each number from $1$ to $n$ appears exactly once).


-----Output-----

Output a single integer denoting the number of ways to delete some prefix and some suffix of each permutation (possibly empty), such that the remaining parts will be equal and non-empty.


-----Examples-----
Input
3 2
1 2 3
2 3 1

Output
4

Input
5 6
1 2 3 4 5
2 3 1 4 5
3 4 5 1 2
3 5 4 2 1
2 3 5 4 1
1 2 3 4 5

Output
5

Input
2 2
1 2
2 1

Output
2



-----Note-----

In the first example, all possible common parts are $[1]$, $[2]$, $[3]$ and $[2, 3]$.

In the second and third examples, you can only leave common parts of length $1$.

Difficulty: interview

Starter code:

Solutions:
#      
import collections, atexit, math, sys, bisect 

sys.setrecursionlimit(1000000)
def getIntList():
    return list(map(int, input().split()))    

try :
    #raise ModuleNotFoundError
    import numpy
    def dprint(*args, **kwargs):
        #print(*args, **kwargs, file=sys.stderr)
        # in python 3.4 **kwargs is invalid???
        print(*args,  file=sys.stderr)
    dprint('debug mode')
except Exception:
    def dprint(*args, **kwargs):
        pass



inId = 0
outId = 0
if inId>0:
    dprint('use input', inId)
    sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
    dprint('use output', outId)
    sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
    atexit.register(lambda :sys.stdout.close())     #idle 中不会执行 atexit
    
N, M= getIntList()

ne = [0 for i in range(N+1) ]
za = getIntList()
for i in range(N-1):
    ne[ za[i]] = za[i+1]
ne[za[-1]] = 0

for _ in range(1, M):
    za = getIntList()
    for i in range(N-1):
        a = za[i]
        b = za[i+1]
        if ne[a] != b:
            ne[a] = -1
    a = za[-1]
    if ne[a]!=0:
        ne[a] = -1

tin = [0 for i in range(N+1) ]

for i in range(1,N+1):
    a = ne[i]
    if a>0:
        tin[a] = 1

res = 0
for i in range(1,N+1):
    if tin[i]: continue
    n = 0
    while i>0:
        n+=1
        i = ne[i]
    res += n * (n+1) //2

print(res)







# -*- coding: utf-8 -*-
"""
created by shhuan at 2018/10/20 22:37

"""

"""
# Definition for a Node.
"""



N, M = list(map(int, input().split()))

A = []
loc = [{} for _ in range(M)]
for i in range(M):
    a = [int(x) for x in input().split()]
    A.append(a)
    for iv, v in enumerate(a):
        loc[i][v] = iv

ans = 0
ls = [0] * M
i = 0
while i < N:
    v = A[0][i]
    ls = [loc[j][v] for j in range(M)]
    segl = 1

    while all([l+segl < N for l in ls]) and all(A[il][l+segl] == A[0][ls[0]+segl] for il, l in enumerate(ls)):
        segl += 1
    ans += segl * (segl + 1) // 2
    i += segl


print(ans)


import sys
input = sys.stdin.readline

n,m=list(map(int,sys.stdin.readline().split()))

A=[list(map(int,sys.stdin.readline().split())) for i in range(m)]

LISTS=[[None for i in range(n+1)] for i in range(m)]

for i in range(n):
    for j in range(m):
        LISTS[j][A[j][i]]=i

ANS=0
i=0
while i<n:
    x=A[0][i]

    check=1
    #print(ANS,i)
    for j in range(i+1,n+1):
        for k in range(1,m):
            if LISTS[k][x]+(j-i)<n and j<n and A[k][LISTS[k][x]+(j-i)]==A[0][j]:
                continue
            else:
                check=0
                break

        if check==0:
            break

    ANS+=(j-i)*(j-i+1)//2
    i=j
    

    
print(ANS)


from sys import stdin
n,m=list(map(int,stdin.readline().strip().split()))
dp=[[-1 for i in range(n+1)] for j in range(m+1)]
for i in range(m):
    s=list(map(int,stdin.readline().strip().split()))
    for j in range(n-2,-1,-1):
        dp[i][s[j]]=s[j+1]
        
dp1=[1 for i in range(n)]
for i in range(n-2,-1,-1):
    t=True
    for j in range(m):
        if dp[j][s[i]]!=s[i+1]:
            t=False
    if t:
        dp1[i]=dp1[i]+dp1[i+1]
print(sum(dp1))
            


def intersection(a, b):
    ret = (max(a[0], b[0]), min(a[1], b[1]))
    if ret[0] >= ret[1]:
        return (-1, -1)
    return ret


def calc(n, m, interval):
    ret = 0
    it_list = [(0, n-1)]
    for i in range(m):
        interval_now = interval[i]
        # print(it_list, interval_now)

        if len(interval_now) == 0:
            return 0
        next_list = []
        # calc
        j = 0
        k = 0
        while j < len(it_list) and k < len(interval_now):
            n1 = it_list[j]
            n2 = interval_now[k]
            inter = intersection(n1, n2)
            if inter[0] == -1:
                if n1[0] < n2[0]:
                    j += 1
                else:
                    k += 1
                continue
            next_list.append(inter)
            if n1[1] < n2[1]:
                j += 1
            else:
                k += 1
        it_list = next_list
        if len(it_list) == 0:
            return 0
    # print(it_list)
    for it in it_list:
        l = it[1] - it[0] + 1
        ret += l*(l+1)//2 - l
    return ret


def main():
    n, m = [int(x) for x in input().split(" ")]
    a = []
    for i in range(m):
        now = list([int(x) for x in input().split(" ")])
        a.append(now)
    ans = n
    if m == 1:
        print(n*(n+1)//2)
        return
    ch = [0 for i in range(n)]
    for i in range(n):
        ch[a[0][i]-1] = i
    for i in range(m):
        for j in range(n):
            a[i][j] = ch[a[i][j]-1]
    interval = []
    for i in range(m):
        a_now = a[i]
        l = 0
        r = 0
        now = []
        for j in range(1, n):
            if a_now[j] == a_now[j-1]+1:
                r += 1
            else:
                if r > l:
                    it = (a_now[l], a_now[r])
                    # print(l, r, it)
                    now.append(it)
                l = j
                r = j
        if r > l:
            it = (a_now[l], a_now[r])
            # print("end", l, r, it)
            now.append(it)
        now = sorted(now, key=lambda x: x[0])
        # print(a_now, now, "\n")
        interval.append(now)
    ans += calc(n, m, interval)
    print(ans)


def __starting_point():
    main()

__starting_point()



def main():
    N, M = [int(x) for x in input().split()]
    arrs = []
    for _ in range(M):
        arrs.append([int(x)-1 for x in input().split()])
    print(solve(N, M, arrs))

def solve(N, M, arrs):
  next_arr = [None] * N
  arr = arrs[0]
  for r, nr in zip(arr, arr[1:]):
      next_arr[r] = nr
  # print(next_arr)
  for i in range(1, M):
      read = arrs[i]
      next_arr_new = [None]*N
      for r, nr in zip(read, read[1:]):
          # print("zipping ", r, nr)
          next_arr_new[r] = nr
      for r, nr in enumerate(next_arr_new):
          if next_arr[r] != nr:
              next_arr[r] = None
              # print("fail", r, nr)
  # print(next_arr)

  starts = []
  cycs = []
  curr = 0
  for r in arr:
      if next_arr[r] != None:
          if curr == 0:
              starts.append(r)
          curr += 1
      elif curr > 0:
          cycs.append(curr)
          curr = 0
  if curr > 0:
      cycs.append(curr)

  assert len(starts) == len(cycs)
  # for s, c in zip(starts, cycs):
  #     print("start ", s, "cyc", c)

  s = 0
  for c in cycs:
      s += c*(c+1) // 2
  s += N

  # print(s)
  return s

solve(3, 2, [[0, 1, 2], [0, 1, 2]])

def solve_naive(r1, r2):
    count = 0
    for i in range(len(r1)):
        for j in range(i+1, len(r1)+1):
            for ii in range(len(r2)):
                l = j-i
                if r1[i:j] == r2[ii:ii+l]:
                    count += 1
    return count

def test(N):
    from random import shuffle
    for i in range(1000):
      r1 = list(range(N))
      r2 = list(range(N))
      shuffle(r1)
      shuffle(r2)
      res = solve(N, 2, [r1, r2])
      res2 = solve_naive(r1, r2)
      if res != res2:
          print(r1, r2)
          print(res, res2)
          assert res == res2

main()


def intersect(seqOne, seqTwo):
	seqOne = sorted(seqOne, key=lambda x: x[0])
	seqTwo = sorted(seqTwo, key=lambda x: x[0])
	i = 0
	j = 0
	ans = []
	while i < len(seqOne) and j < len(seqTwo):
		a,b = seqOne[i]
		c,d = seqTwo[j]
		if max(a,c) < min(b,d):
			ans.append( (max(a,c), min(b,d)) )
		if b < d:
			i += 1
		else:
			j += 1
	return ans

def main():
	n,m = map(int, input().strip().split())
	orders = []
	for i in range(m):
		orders.append([int(x) for x in input().strip().split()])
	
	ind = [0] * (n+1)
	for i in range(1,n+1):
		ind[orders[0][i-1]] = i

	subseqs = [(1,n)]
	for i in range(1,m):
		order = list(map(lambda x: ind[x], orders[i]))
		i = 0
		currSubseqs = []
		for j in range(1,n):
			if order[j] == order[j-1] + 1:
				continue
			else:
				if j - i > 1:
					currSubseqs.append( (order[i], order[j-1]) )
				i = j
		if i != n-1:
			currSubseqs.append( (order[i], order[j]) )

		subseqs = intersect(subseqs, currSubseqs)
		if len(subseqs) == 0:
			break

	ans = n
	for subseq in subseqs:
		x,y = subseq
		m = (y - x + 1)
		ans += m * (m + 1) // 2 - m

	print(ans)	
	


def __starting_point():
	main()
__starting_point()

#!/usr/bin/env python3
# encoding: utf-8



#----------
# Constants
#----------



#----------
# Functions
#----------

def summarize(val):
    return (val + 1) * val // 2


# The function that solves the task
def calc(data):
    m = len(data)
    n = len(data[0])

    reflections = []
    for i in range(m):
        reflections.append(dict())
        r = reflections[-1]
        for j in range(n):
            r[data[i][j]] = j

    lengths = []
    index = 0
    while index < n:
        val = data[0][index]
        ln = 1
        indexes = [ reflections[i][val] for i in range(1, m) ]
        for k in range(index+1, n):
            d = k - index
            equal = True
            val = data[0][k]
            for i in range(1, m):
                if indexes[i-1] + d >= n or data[i][indexes[i-1] + d] != val:
                    equal = False
                    break
            if equal:
                ln += 1
            else:
                break
        lengths.append(summarize(ln))
        index += ln

    return sum(lengths)


# Reads a string from stdin, splits it by space chars, converts each
# substring to int, adds it to a list and returns the list as a result.
def get_ints():
    return [ int(n) for n in input().split() ]


# Reads a string from stdin, splits it by space chars, converts each substring
# to floating point number, adds it to a list and returns the list as a result.
def get_floats():
    return [ float(n) for n in input().split() ]


def seq2str(seq):
    return ' '.join(str(item) for item in seq)


#----------
# Execution start point
#----------

def __starting_point():
    a = get_ints()
    assert len(a) == 2
    n, m = a[0], a[1]

    data = []
    for i in range(m):
        a = get_ints()
        assert len(a) == n
        data.append(a)

    res = calc(data)
    print(res)

__starting_point()

n,m = map(int,input().split())
initial = []
first = input().split()
for i in range(n):
    initial.append(int(first[i]))
rest = []
for i in range(m-1):
    current = []
    nfirst = input().split()
    for j in range(n):
        current.append(int(nfirst[j]))
    rest.append(current)
index = 0
compar = 0
ans = 0
indices = []
for i in range(m-1):
    temp = [0]*n
    x = rest[i]
    for j in range(n):
        temp[x[j]-1] = j
    indices.append(temp)
while index < n:
    compar = initial[index]
    cur = [0]*(m-1)
    count = 1
    lol = n-index
    for k in range(m-1):
        cur[k] = indices[k][compar-1]
        lol = min(lol,n-cur[k])
    done = False
    while count < lol:
        for k in range(m-1):
            x = rest[k]
            j = cur[k]
            if x[j+count] != initial[index+count]:
                done = True
                break
        if done:
            break
        count += 1
    ans += (count*(count+1))//2
    index += count
print(ans)

n,m = list(map(int,input().split()))
initial = []
first = input().split()
for i in range(n):
    initial.append(int(first[i]))
rest = []
for i in range(m-1):
    current = []
    nfirst = input().split()
    for j in range(n):
        current.append(int(nfirst[j]))
    rest.append(current)
index = 0
compar = 0
ans = 0
indices = []
for i in range(m-1):
    temp = [0]*n
    x = rest[i]
    for j in range(n):
        temp[x[j]-1] = j
    indices.append(temp)
while index < n:
    compar = initial[index]
    cur = [0]*(m-1)
    count = 1
    lol = n-index
    for k in range(m-1):
        cur[k] = indices[k][compar-1]
        lol = min(lol,n-cur[k])
    done = False
    while count < lol:
        for k in range(m-1):
            x = rest[k]
            j = cur[k]
            if x[j+count] != initial[index+count]:
                done = True
                break
        if done:
            break
        count += 1
    ans += (count*(count+1))//2
    index += count
print(ans)
                   


from collections import defaultdict
from collections import deque

(n, m) = [int(x) for x in input().split()]
messages = []
for i in range(m):
    temp = [int(x) for x in input().split()]
    messages.append(temp)


seq = defaultdict(lambda: 0)
pairs = {}
for k in range(n - 1):
    pairs[messages[0][k]] = messages[0][k + 1]


for i in range(1, m):
    for k in range(n-1):
        temp = messages[i][k]
        if pairs.get(temp, None) != messages[i][k+1]:
            pairs.pop(temp, None)
    pairs.pop(messages[i][n-1], None)



sequences = []
starts = set(pairs.keys())
ends = set(pairs.values())
conn = starts & ends

for key, value in list(pairs.items()):

    if key in conn:
        continue
    val = value
    temp = []
    temp.append(key)
    temp.append(value)
    while val in starts:
        val = pairs[val]
        temp.append(val)

    sequences.append(temp)


# print(sequences)


variants = n

for seq in sequences:
    l = len(seq)
    variants+=l*(l-1)//2

print(variants)






n,m=list(map(int,input().split()))
arr=[]
arr1=[]
for i in range(m):
    arrx=list(map(int,input().split()))
    arry=[0]*n
    for j in range(n):
        arry[arrx[j]-1]=j+1
    arr.append(arrx)
    arr1.append(arry)

ans=n
i=0
j=1
flag=0
while(i<n-1 and j<n):
    k1=arr[0][i]
    k2=arr[0][j]
    l=0
    while(l<m):
        #print(arr[0][i+k]-1,arr[0][i+k+1]-1,'YO',flag,l)
        if(arr1[l][arr[0][j-1]-1]!=arr1[l][arr[0][j]-1]-1):
            flag=1
            break
        #print(flag)
        if(flag==1):
            break
        l+=1
    if(flag==1):
        ans+=((j-i)*(j-i+1))//2
        ans-=j-i
        i=j
        j+=1
        flag=0
    else:
        j+=1
    #print(i,j)
if(flag==0):
    ans+=((j-i)*(j-i+1))//2
    ans-=j-i
print(ans)


def main():
    n, m = [int(c) for c in input().split()]
    if m == 1:
        print(n * (n + 1) // 2)
        return
    
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)]

    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = 0, 1
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                for k, j in enumerate(list(range(start+1, i)), 1):
                    seq_map[t[j]] = seq_map[t[start]] - k
                start = i
                seq_map[t[start]] = 1
            i += 1

        for k, j in enumerate(list(range(start+1, i)), 1):
            seq_map[t[j]] = seq_map[t[start]] - k
        
        counters.append(seq_map)

    

    ans = 0
    for i in range(n):
        _min = min([cnt[i] for cnt in counters])
        ans += _min

    # ans = sum([min([cnt[i] for cnt in counters]) for i in range(n)])
    print(ans)
        

def __starting_point():
    main()

__starting_point()

def main():
    n, m = [int(c) for c in input().split()]
    if m == 1:
        print(n * (n + 1) // 2)
        return
    
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(m)]

    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = 0, 1
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                cnt = seq_map[t[start]]
                for j in range(start+1, i):
                    cnt -= 1
                    seq_map[t[j]] = cnt
                    
                start = i
                seq_map[t[start]] = 1
            i += 1

        cnt = seq_map[t[start]]
        for j in range(start+1, i):
            cnt -= 1
            seq_map[t[j]] = cnt
            
        counters.append(seq_map)

    ans = sum([min([cnt[i] for cnt in counters]) for i in range(n)])
    print(ans)
        

def __starting_point():
    main()

__starting_point()

def main():
    n, m = [int(c) for c in input().split()]
    if m == 1:
        print(n * (n + 1) // 2)
        return
    
    testimonies = [[int(c) for c in input().split()] for _ in range(m)]
    perm_map = {client: i for i, client in enumerate(testimonies[0])}
    testimonies = [[perm_map[client] for client in testimonies[i]] for i in range(1, m)]

    counters = []
    for t in testimonies:
        seq_map = [0] * n
        start, i = 0, 1
        seq_map[t[start]] = 1
        while i < len(t):
            if t[i] - t[i - 1] == 1:
                seq_map[t[start]] += 1
            else:
                cnt = seq_map[t[start]]
                for j in range(start+1, i):
                    cnt -= 1
                    seq_map[t[j]] = cnt
                    
                start = i
                seq_map[t[start]] = 1
            i += 1

        cnt = seq_map[t[start]]
        for j in range(start+1, i):
            cnt -= 1
            seq_map[t[j]] = cnt
            
        counters.append(seq_map)

    ans = sum([min([cnt[i] for cnt in counters]) for i in range(n)])
    print(ans)
        

def __starting_point():
    main()

__starting_point()

n, m = map(int, input().split())
a = []
for i in range(m):
  a.append(list(map(int, input().split())))
b = [set([]) for i in range(n)]
for i in range(n):
  for j in range(m):
    ya = a[j][i]
    if i == n-1:
      b[ya-1].add(100000000)
    else:
      b[ya-1].add(a[j][i+1])
class UnionFind():
    def __init__(self,size):
        self.table = [-1 for _  in range(size)]

    def find(self,x):
        while self.table[x] >= 0:
            x = self.table[x]
        return x

    def union(self,x,y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] != self.table[s2]:
                if self.table[s1] < self.table[s2]:
                    self.table[s2] = s1
                else:
                    self.table[s1] = s2
            else:
                self.table[s1] += -1
                self.table[s2] = s1
        return
UN = UnionFind(n)
for i in range(n):
  if len(b[i]) == 1 and list(b[i])[0] !=100000000:
    UN.union(i,list(b[i])[0]-1)
d = [0]*n
for i in range(n):
  d[UN.find(i)] += 1
ans = 0
for i in range(n):
  ans += (d[i]-1)*(d[i])//2
print(ans+n)

def get_sub_array(array):
    d = {}
    st = 0
    en = 0
    while st < len(array) and en < len(array):
        if en < (len(array)-1) and array[en+1] == array[en]+1:
            en += 1
        else:
            d[array[st]] = en-st+1
            st += 1
            en = st if en < st else en
    return d
n, m = [int(x) for x in input().split()]
array = []
for i in range(m):
    array.append([int(x) for x in input().split()])
d = dict()
for i in range(1, n + 1):
    d[array[0][i-1]] = i
for i in range(m):
    for j in range(n):
        array[i][j] = d[array[i][j]]
res = [float("inf") for i in range(n)]
dm = []
for i in range(m):
    dm.append(get_sub_array(array[i]))
for i in range(1, n+1):
    for j in range(m):
        res[i-1] = min(res[i-1], dm[j][i])
print(sum(res))



n, m = list(map(int, input().split()))

graph = [0] * n
_next = [True] * n
_next[n - 1] = False

def read_array():
    return list([x - 1 for x in list(map(int, input().split()))])


first = read_array()
for i in range(n):
    graph[first[i]] = i

for cnt in range(1, m):
    a = read_array()
    for i in range(n - 1):
        if graph[a[i]] + 1 != graph[a[i + 1]]:
            _next[graph[a[i]]] = False
    _next[graph[a[n - 1]]] = False

l = 0
ans = 0
for cnt in range(n):
    l += 1
    if not _next[cnt]:
        ans += (l * (l + 1)) // 2
        l = 0

print(ans)


n, m = list(map(int, input().split()))

graph = [0] * n
_next = [True] * n
_next[n - 1] = False

def read_array():
    return list([x - 1 for x in list(map(int, input().split()))])


first = read_array()
for i in range(n):
    graph[first[i]] = i

for cnt in range(1, m):
    a = read_array()
    for i in range(n - 1):
        if graph[a[i]] + 1 != graph[a[i + 1]]:
            _next[graph[a[i]]] = False
    _next[graph[a[n - 1]]] = False

l = 0
ans = 0
for cnt in range(n):
    l += 1
    if not _next[cnt]:
        ans += (l * (l + 1)) // 2
        l = 0

print(ans)


n, m = list(map(int, input().split()))

graph = [0] * n
_next = [True] * n
_next[n - 1] = False

def read_array():
    return list([x - 1 for x in list(map(int, input().split()))])


first = read_array()
iterable1 = list(range(n))
iterable2 = list(range(n - 1))
for i in iterable1:
    graph[first[i]] = i

for cnt in range(1, m):
    a = read_array()
    for i in range(n - 1):
        if graph[a[i]] + 1 != graph[a[i + 1]]:
            _next[graph[a[i]]] = False
    _next[graph[a[n - 1]]] = False

l = 0
ans = 0
for cnt in iterable1:
    l += 1
    if not _next[cnt]:
        ans += (l * (l + 1)) // 2
        l = 0

print(ans)


I=lambda:list(map(int,input().split()))
n,m=I()
a=[[]]*10
indexwaliarray=[[0 for i in range(n)]for _ in range(m)]
#print(indexwaliarray)
for i in range(m):
    a[i]=list(I())
for i in range(m):
    for j in range(n):
        indexwaliarray[i][a[i][j]-1]=j
answaliarray=[[a[0][i]-1,a[0][i+1]-1 ] for i in range(n-1)]
#print(answaliarray)
for i in range(n-1):
    for j in range(1,m):
        if indexwaliarray[j][answaliarray[i][1]]!=indexwaliarray[j][answaliarray[i][0]]+1:
            answaliarray[i]=[-1,-1]
#print(answaliarray)
count=[]
c=0
for i in range(n-1):
    if answaliarray[i]==[-1,-1]:
        if c!=0:
            count.append(c)
            c=0
    else :
        c+=1
        
if c!=0:
    count.append(c)
#print(count)                        
yepakkaanshai=0
for i in count:
    yepakkaanshai+=((i+1)*i)//2
print(yepakkaanshai+n)    



n, m = list(map(int, input().split()))

graph = [0] * n
_next = [True] * n
_next[-1] = False

def read_array():
	return list([x-1 for x in list(map(int, input().split()))])

first = read_array()


for i in range(n):
	graph[first[i]] = i

for _ in range(1, m):
	a = read_array()
	for i in range(n - 1):


		if graph[a[i]] + 1 != graph[a[i+1]]:
			_next[graph[a[i]]] = False
	_next[graph[a[n-1]]] = False

l = 0
ans = 0
for _ in range(n):
	l += 1
	if not _next[_]:
		ans += (l * (l + 1)) // 2
		l = 0

print (ans)



n, m = [int(i) for i in input().split(' ')]

import sys

fconnection = [None] * n
bconnection = [None] * n

if m == 1:
    print(int((n+1)*n/2))
    return

svidetel = input().split(' ')
p = int(svidetel[0])-1
for current_pok in svidetel[1:]:
    q = int(current_pok)-1
    fconnection[p] = q
    bconnection[q] = p
    p = q


for i in range(m-1):
    svidetel = input().split(' ')
    p = int(svidetel[0])-1
#    try:
#        fconnection[fconnection.index(p)] = None
#    except ValueError:
#        pass
    bconnection[p] = None
    for current_pok in svidetel[1:]:
        q = int(current_pok)-1
        if fconnection[p] != q:
            fconnection[p] = None
        if bconnection[q] != p:
            bconnection[q] = None
        p = q
    fconnection[p] = None
#    try:
#        bconnection[bconnection.index(p)] = None
#    except ValueError:
#        pass




is_bundled = [True] + [False] * (n - 1)
unbundled_count = n
current_bundle = []
number_of_variants = 0
research_deck = [0]

for i in range(n):
    if (fconnection[i] == None) and (bconnection[i] == None):
        number_of_variants += 1 # one distinct node
    elif bconnection[i] == None:
        # this is start of new run. check it.
        number_in_run = 1
        next_in_run = fconnection[i]
        while next_in_run is not None:
            number_in_run += 1
            next_in_run = fconnection[next_in_run]
        number_of_variants += int((1 + number_in_run) * number_in_run / 2)


#while unbundled_count >= 0:
#    #print(research_deck, current_bundle)
#    if research_deck:
#        c = research_deck.pop()
#        # check _to connection
#        if (connection[c] != None) and not is_bundled[connection[c]]:
#            research_deck.append(connection[c])
#        # check _from connection
#        try:
#            fr = connection.index(c)
#            if not is_bundled[fr]:
#                research_deck.append(fr)
#        except ValueError:
#            pass
#        current_bundle.append(c)
#        is_bundled[c] = True
#    else:
#        curlen = len(current_bundle)
#        number_of_variants += int((curlen + 1)*curlen/2)
#        unbundled_count -= curlen
#        current_bundle = []
#        if unbundled_count > 0:
#            research_deck = [is_bundled.index(False)]
#        else:
#            break
print(number_of_variants)