#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define sz(v) (int)v.size()
#define all(v) v.begin(), v.end()
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template < typename T_container, typename T = typename enable_if < !is_same<T_container, string>::value, typename T_container::value_type >::type >
ostream & operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
void dbg_out() { cerr << "\b\b]\n"; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << H << ", "; dbg_out(T...);}
// #define LM10_Piyush
#ifdef LM10_Piyush
#define watch(...) cerr << "[" << #__VA_ARGS__ << "]: [", dbg_out(__VA_ARGS__)
#else
#define watch(...)
#endif

vector <string> split(string s, char delim) {
    vector <string> v;
    stringstream ss(s);
    while (ss.good()) {
        string stk;
        getline(ss, stk, delim);
        if (stk.empty()) continue;
        v.push_back(stk);
    }
    return v;
}

const string haha = "haha";

int check(string s) {
    int ans = 0;
    for (int j = 0; j + 4 <= sz(s); ++j) {
        string b = s.substr(j, 4);
        if (b == haha)
            ans++;
    }
    return ans;
}

void solve() {
    int n; cin >> n; cin.get();
    map <string, pair<string, ll>> mp;
    for (int i = 1; i <= n; ++i) {
        string s;
        getline(cin, s);
        vector <string> vs = split(s, ' ');
        if (sz(vs) == 3) {
            s = vs[2];
            if (sz(s) >= 3) {
                s = s.substr(0, 3) + "+" +  s.substr(sz(s) - 3, 3);
            }
            mp[vs[0]] = {s, check(vs[2])};
        }
        else {
            if (!mp.count(vs[2]))
                mp[vs[2]] = {"", 0};
            if (!mp.count(vs[4]))
                mp[vs[4]] = {"", 0};
            ll tot = mp[vs[2]].second + mp[vs[4]].second;
            string s1 = mp[vs[2]].first;
            string s2 = mp[vs[4]].first;
            s = s1 + s2;
            tot += check(s);
            if (sz(s) >= 3) {
                s1 = s.substr(0, 3);
                s2 = s.substr(sz(s) - 3, 3);
                s = s1 + "+" + s2;
            }
            mp[vs[0]] = {s, tot};
        }
        if (i == n) {
            cout << mp[vs[0]].second << endl;
        }
    }
}

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

    int t; cin >> t;
    while (t--) {
        solve();
    }

    return 0;
}


/*

*/