#include <bits/stdc++.h>
#ifdef LOCAL
#include "code/formatting.hpp"
#else
#define debug(...) (void)0
#endif

using namespace std;
static_assert(sizeof(int) == 4 && sizeof(long) == 8);

int main() {
    ios::sync_with_stdio(false), cin.tie(nullptr);
    int T;
    cin >> T;
    for (int case_num = 1; case_num <= T; case_num++) {
        int N, M;
        cin >> N >> M;

        vector<vector<int>> P(N + 1, vector<int>(M));
        for (int i = 0; i <= N; i++) {
            for (int j = 0; j < M; j++) {
                cin >> P[i][j];
            }
            sort(begin(P[i]), end(P[i]));
        }

        vector<int> state = P[0];
        vector<bool> special(M, true);
        map<int, set<int>> where_special, where_other;
        for (int j = 0; j < M; j++) {
            where_special[state[j]].insert(j);
        }

        auto remove = [&](auto& mm, int i, int j) {
            if (mm.at(i).size() == 1) {
                mm.erase(i);
            } else {
                mm.at(i).erase(j);
            }
        };

        int ans = 0;

        for (int i = 1; i <= N; i++) {
            vector<int> rem, add;
            int x = 0, y = 0;
            while (x < M && y < M) {
                if (P[i - 1][x] == P[i][y]) {
                    x++, y++;
                } else if (P[i - 1][x] < P[i][y]) {
                    rem.push_back(P[i - 1][x]), x++;
                } else {
                    add.push_back(P[i][y]), y++;
                }
            }
            while (x < M) {
                rem.push_back(P[i - 1][x]), x++;
            }
            while (y < M) {
                add.push_back(P[i][y]), y++;
            }

            assert(rem.size() == add.size());
            int S = rem.size();
            if (S == 0) {
                continue;
            }

            vector<int> redressed;

            for (int z = 0; z < S; z++) {
                int r = rem[z], a = add[z];

                if (where_special.count(r)) {
                    int j = *where_special[r].begin();
                    remove(where_special, r, j);
                    redressed.push_back(j);
                    state[j] = a;
                } else {
                    int j = *where_other[r].begin();
                    remove(where_other, r, j);
                    redressed.push_back(j);
                    state[j] = a;
                    ans++;
                }
            }

            for (int j : redressed) {
                where_other[state[j]].insert(j);
            }
        }

        cout << "Case #" << case_num << ": " << ans << '\n';
    }
    return 0;
}
