package main
import (
"bufio"
"bytes"
"fmt"
"os"
)
type FastScanner struct {
r *bufio.Reader
}
func NewFastScanner() *FastScanner {
return &FastScanner{r: bufio.NewReaderSize(os.Stdin, 1<<20)}
}
func (fs *FastScanner) NextInt() int {
sign, val := 1, 0
c, err := fs.r.ReadByte()
for (c < '0' || c > '9') && c != '-' {
c, err = fs.r.ReadByte()
if err != nil {
return 0
}
}
if c == '-' {
sign = -1
c, _ = fs.r.ReadByte()
}
for c >= '0' && c <= '9' {
val = val*10 + int(c-'0')
c, err = fs.r.ReadByte()
if err != nil {
return sign * val
}
}
fs.r.UnreadByte()
return sign * val
}
func main() {
in := NewFastScanner()
t := in.NextInt()
var out bytes.Buffer
for ; t > 0; t-- {
n := in.NextInt()
m := in.NextInt()
total := n * m
a := make([]int, total)
for i := 0; i < total; i++ {
a[i] = in.NextInt()
}
row := make([]int, m)
pos := 0
ans := 0
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
row[j] = in.NextInt()
}
v := a[pos]
p := -1
for j := 0; j < m; j++ {
if row[j] == v {
p = j
break
}
}
keep := 0
if p != -1 {
cand := m - p
ok := true
for j := 0; j < cand; j++ {
if a[pos+j] != row[p+j] {
ok = false
break
}
}
if ok {
keep = cand
}
}
ans += m - keep
pos += keep
}
fmt.Fprintln(&out, ans)
}
fmt.Print(out.String())
}