#include <bits/stdc++.h>
using namespace std;
string pat="haha";
int pattern_find(string txt)
{
    long long int found = txt.find(pat),ans=0;
    while (found != string::npos) {
        ans++;
        found = txt.find(pat, found + 1);
    }
    return ans;
}
string first_th(string s)
{
    if(s.size()<3) return s;
    return s.substr(0,3);
}
string last_th(string s)
{
    if(s.size()<3) return s;
    return s.substr(s.size()-3,3);
}
int main()
{
   int test;
   cin >> test;
   while(test--)
   {
       map<string,string>mmap;
   map<string,long long int>total;
   long long int n;
   cin >> n;
   string s,type,p,sign,d,ans;
   while(n--)
   {
       cin >> s >> type >> p;
       if(type==":=")
       {
           total[s]=pattern_find(p);
           mmap[s]=p;
       }
       else
       {
           cin >> sign >> d;
           total[s]=total[d]+total[p]+pattern_find(last_th(mmap[p])+first_th(mmap[d]));
           mmap[s]=mmap[p]+mmap[d];
           //total[s]=pattern_find(mmap[s]);
           if(mmap[s].size()>=7)
           {
               p=mmap[s];
               mmap[s]=first_th(p)+"@"+last_th(p);
           }
       }
       ans=s;
   }
   cout << total[ans] << endl;
   }
}
