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

#define int int64_t



class info
{
public:
    int freq;
    string to_consider;

    info() {
        this->freq = 0;
        this->to_consider = "";
    }

    info(const string& s) {
        this->freq = count(s);
        this->to_consider = s;
    }

    info(const info& x, const info& y) {
        this->freq = x.freq + y.freq;
        this->freq += count(get_suffix(x.to_consider) + get_prefix(y.to_consider));
        this->to_consider = x.to_consider + y.to_consider;
        if(int(this->to_consider.size()) > 7) {
            string pre = get_prefix(this->to_consider);
            string suf = get_suffix(this->to_consider);
            this->to_consider = pre + "#" + suf;
        }
    }

    string get_prefix(const string& s) {
        int N = min(int(3), int(s.size()));
        string ans = "";
        for(int i = 0; i < N; i++) {
            assert(s[i] != '#');
            ans.push_back(s[i]);
        }
        return ans;
    }

    string get_suffix(const string& r) {
        string s = r;
        reverse(s.begin(), s.end());
        int N = min(int(3), int(s.size()));
        string ans = "";
        for(int i = 0; i < N; i++) {
            assert(s[i] != '#');
            ans.push_back(s[i]);
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }

    int count(const string& s) {
        int freq = 0;
        for(int i = 0; i + 3 < int(s.size()); i++) {
            if(s.substr(i, 4) == "haha")
                freq++;
        }
        return freq;
    }
};

void gogo() {
    int n;
    cin >> n;
    map<string, info> m;
    string last = "";
    for(int i = 0; i < n; i++) {
        string var1, op;
        cin >> var1 >> op;
        if(op == ":=") {
            string actual_string;
            cin >> actual_string;
            info extract(actual_string);
            m[var1] = extract;
        }
        else {
            string var2, op2, var3;
            cin >> var2 >> op2 >> var3;
            info extract(m[var2], m[var3]);
            m[var1] = extract;
        }
        if(i == n - 1)
            last = var1;
        // cout << i << ": " << endl;
        // for(auto [s, x] : m)
        //     cout << s << ' ' << x.freq << ' ' << x.to_consider << endl;
    }
    cout << m[last].freq << endl;
    
    
}

int32_t main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    
    int tc = 1;
    cin >> tc;
    while(tc--) gogo();

    return 0;
}