//Hoang Son WIBU lolicon codeforces rate 1604 khong cay
#include <bits/stdc++.h>
#define F first
#define S second
#define times double stime = clock();
#define gettime cerr << "\nTime executed: " << (clock() - stime) / CLOCKS_PER_SEC * 1000 << "ms.\n";
using namespace std;
typedef long long ll;
typedef double dou;
typedef pair<ll, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
const ll mod = 1000000009;
int n;
string a, ty, b, tad, c;
map<string, string> val;
map<string, ll> val2;
string chee = "haha";
string lat;
ll conutS(string &ax){
ll ans = 0;
for(int i = 0; i + 4 <= (int)ax.size(); i++){
bool ok = true;
for(int j = i; j<i+4; j++){
if(ax[j] != chee[j - i]){
ok = false;
break;
}
}
if(ok) ans++;
}
return ans;
}
ll conutSLR(string &ax, int l, int r){
ll ans = 0;
for(int i = l; i + 4 <= r; i++){
bool ok = true;
for(int j = i; j<i+4; j++){
if(ax[j] != chee[j - i]){
ok = false;
break;
}
}
if(ok) ans++;
}
return ans;
}
void process(){
int t;
cin >> t;
while(t--){
val.clear();
val2.clear();
cin >> n;
lat = "";
for(int i = 1; i<=n; i++){
cin >> a >> ty >> b;
if(ty == ":="){
val[a] = b;
val2[a] = conutS(b);
} else {
cin >> tad >> c;
string nes = val[b] + val[c];
ll addans = conutSLR(nes, max((int)val[b].size() - 3, 0), min((int)val[b].size() + 3, (int)nes.size()));
if(nes.size() >= 6){
string nes2 = "";
for(int i = 0; i<3; i++) nes2 += nes[i];
for(int i = 2; i>=0; i--) nes2 += nes[(int)nes.size() - 1 - i];
nes = nes2;
}
val[a] = nes;
val2[a] = val2[b] + val2[c] + addans;
}
if(i == n) lat = a;
}
cout << val2[lat] << "\n";
}
}
int online = 2;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
if (online == 0) {
freopen("in.inp", "r", stdin);
freopen("out.out", "w", stdout);
} else if (online == 1) {
freopen(".inp", "r", stdin);
freopen(".out", "w", stdout);
}
// times
process();
// gettime
return 0;
}