#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef tuple<ll, string, string> word;

map<string, word> memory;

ll count_haha(string w)
{
    if (w.length() < 4) return 0;

    ll cnt = 0;
    for (int i = 0; i <= w.length() - 4; i++)
    {
        if (w.substr(i, 4) == "haha") cnt++;
    }

    return cnt;
}

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

    int tests;
    cin >> tests;
    while (tests--)
    {
        int N;
        cin >> N;
        cin.ignore();

        memory.clear();

        string final_key;
        while (N--)
        {
            string line;
            getline(cin, line);

            stringstream ss(line);
            vector<string> segments;
            string part;

            while (ss >> part) segments.push_back(part);

            if (segments[1] == ":=")
            {
                int len = segments[2].length();

                ll cnt = count_haha(segments[2]);
                string pref = segments[2].substr(0, min(len, 3));
                string suff = segments[2].substr(max(0, len - 3), min(len, 3));

                memory[segments[0]] = make_tuple(cnt, pref, suff);
            }
            else
            {
                word a = memory[segments[2]];
                word b = memory[segments[4]];

                string comb = get<2>(a) + get<1>(b);
                int len = comb.size();

                ll cnt = get<0>(a) + get<0>(b) + count_haha(comb);
                string pref = (len < 6) ? comb.substr(0, min(len, 3)) : get<1>(a);
                string suff = (len < 6) ? comb.substr(max(0, len - 3), min(len, 3)) : get<2>(b);

                memory[segments[0]] = make_tuple(cnt, pref, suff);
            }

            final_key = segments[0];
        }

        cout << get<0>(memory[final_key]) << "\n";
    }

    return 0;
}