#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int maxn = 3e5 + 5;
const ll inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
ll get_count(const string &s) {
    int pos = s.find("haha");
    ll sum = 0;
    while (pos != string::npos) {
        pos = s.find("haha", pos + 1);
        ++sum;
    }
    return sum;
}
ll get_count(const string &a, const string &b) {
    ll sum = 0;
    for (int i = 1; i <= 3; ++i) {
        if (i > a.length()) continue;
        if (4 - i > b.length()) continue;
        sum += (a.substr(a.length() - i) + b.substr(0, 4 - i) == "haha");
    }
    return sum;
}
string change(const string &r) {
    if (r.length() <= 6) return r;
    return r.substr(0, 3) + r.substr(r.length() - 3);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    int T;
    cin >> T;
    while (T--) {
        int n;
        cin >> n;
        string s;
        map<string, pair<string, ll>> mp;
        ll ans = 0;
        getline(cin, s);
        while (n--) {
            getline(cin, s);
            stringstream ss(s);
            string l;
            ss >> l;
            ss >> s;
            if (s == ":=") {
                string r;
                ss >> r;
                if (r.length() <= 6) {
                    mp[l] = make_pair(r, get_count(r));
                } else {
                    mp[l] = make_pair(r.substr(0, 3) + r.substr(r.length() - 3),
                                      get_count(r));
                }
            } else {
                string a, b;
                ss >> a >> b >> b;
                ll A = mp[a].second, B = mp[b].second;
                a = mp[a].first;
                b = mp[b].first;
                mp[l] = make_pair(change(a + b), A + B + get_count(a, b));
            }
            ans = mp[l].second;
        }
        cout << ans << endl;
    }
    return 0;
}
