#include <iostream>
#include <cctype>
#include <cstring>
#include <set>
#include <queue>
#include <climits>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <stack>
#include <string>
#include <unordered_map>
#include <map>
#include <list>
#include <iomanip>
#include <ctype.h>
#include <stdio.h>
//****DEFINE****//
#define mod 1000000007
#define pie 3.141592653589793238
#define all(x) x.begin(), x.end()
template <typename A, typename B>
A amax(A &a, B b)
{
    if (b > a)
        a = b;
    return a;
}
template <typename A, typename B>
A amin(A &a, B b)
{
    if (b < a)
        a = b;
    return a;
}
using namespace std;
typedef long long ll;
//****FUNCTIONS****//
bool cmd1(pair<ll, ll> a, pair<ll, ll> b)
{
    if (a.second > b.second)
    {
        return true;
    }
    return false;
}
bool cmd2(int a, int b)
{
    if (a > b)
    {
        return true;
    }
    return false;
}
//**********   TO TAKE INPUT FROM A FILE   ************
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
int dfs(int root, vector<vector<int> > &adj1, vector<int> &vis)
{
    int cnt = 1;
    vis[root] = 1;
    for (auto it : adj1[root])
    {
        if (vis[it] == 0)
        {
            cnt += dfs(it, adj1, vis);
        }
    }
    return cnt;
}
void meena()
{
    int n;
    cin >> n;
    map<string, set<int> > adj;
    map<string, set<int> > adj2;
    for (int i = 0; i < n; i++)
    {
        string x, y;
        cin >> x >> y;
        adj[x].insert(i);
        adj2[y].insert(i);
    }
    vector<vector<int> > adj1(n);
    for (auto it : adj)
    {
        set<int> temp = it.second;
        int prev = -1;
        for (auto it1 : temp)
        {
            if (prev == -1)
            {
                prev = it1;
            }
            else
            {
                adj1[it1].push_back(prev);
                adj1[prev].push_back(it1);
                prev = it1;
            }
        }
    }
    for (auto it : adj2)
    {
        set<int> temp = it.second;
        int prev = -1;
        for (auto it1 : temp)
        {
            if (prev == -1)
            {
                prev = it1;
            }
            else
            {
                adj1[it1].push_back(prev);
                adj1[prev].push_back(it1);
                prev = it1;
            }
        }
    }
    vector<int> vis(n, 0);
    int cnt = 0;
    for (int i = 0; i < n; i++)
    {
        if (vis[i] == 0)
        {
            cnt = max(dfs(i, adj1, vis), cnt);
        }
    }
    cout << n - cnt;
    cout << endl;
}
int main()
{

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int po;
    cin >> po;
    //    po=1;

    while (po--)
    {
        meena();
    }
}