#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll cal(string s) {
    ll res = 0;
    for (int i = 0; i + 4 <= s.length(); i++) {
        auto t = s.substr(i, 4);
        res += ("haha" == t);
    }
    return res;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        map<string, pair<ll, string>> mp;
        string last;
        for (int i = 0; i < n; i++) {
            string a, op, b, c;
            cin >> a >> op >> b;
            if (op == ":=") {
                mp[a] = { cal(b),b };
            } else {
                cin >> c >> c;
                auto concat = [&](pair<ll, string> a, pair<ll, string> b) {
                    ll cnt = a.first + b.first;
                    string c;
                    if (a.second.length() > 3) {
                        c = a.second[a.second.length() - 3];
                        c += a.second[a.second.length() - 2];
                        c += a.second[a.second.length() - 1];
                    } else {
                        c = a.second;
                    }
                    for (int i = 0; i < min((int)b.second.length(), 3); i++) {
                        c.push_back(b.second[i]);
                    }
                    cnt += cal(c);
                    c = a.second + b.second;
                    if (c.length() >= 6) {
                        c.erase(c.begin() + 3, c.end() - 3);
                    }
                    return make_pair(cnt, c);
                };
                mp[a] = concat(mp[b], mp[c]);
            }
            last = a;
        }
        cout << mp[last].first << "\n";
    }
    return 0;
}
