#include<bits/stdc++.h>
using namespace std;
long long i,j,p,q,n,k,d,t,d1,d2,D;
struct Pic
{
	string sl,sr;
	long long br;
}a[106];

string s,f,f1,f2;
Pic izch(string s)
{
	int ds=s.size()-1,k;
	string ss;long long br=0;
	for(k=0;k<=ds-3;k++)
	{
		ss=s.substr(k,4);
		if(ss=="haha")
		{
			br++;
			k++;	
		}
	}
	k=min(3,ds+1);
	return  {s.substr(0,k),s.substr(ds-k+1,k),br};
}
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	//cout<<izch("hahaha").sl<<" "<<izch("hahaha").sr<<" "<<izch("hahaha").br<<endl;
	cin>>t;
	while(t--)
	{
		map <string,int> m;
		D=0;		
		cin>>n;
		cin.ignore();
		for(i=1;i<=n;i++)
		{
			getline(cin,s);
			d=s.size()-1;
			j=0;
			f="";f1="";f2="";
			while(s[j]!=' ')
			{
				f=f+s[j];
				j++;
			}
			j++;
			if(s[j]==':')
			{
				///prisvoqvane na stoinost
				j+=3;
				while(j<=d)
				{
					f1=f1+s[j];
					j++;
				}
				/// f = f1
				//cout<<f<<" "<<f1<<endl;
				Pic danni = izch(f1);
				if(m[f]!=0)
				{
					a[m[f]] = danni;
				}
				else
				{
					D++;
					m[f]=D;
					a[D]=danni;
				}		
			}
			else
			{
				///sbor
				j+=2;
				while(s[j]!=' ')
				{
					f1=f1+s[j];
					j++;
				}
				j+=3;
				while(j<=d)
				{
					f2=f2+s[j];
					j++;
				}
				///f = f1 + f2
				//cout<<f1<<" "<<f2<<endl;
				string sum = a[m[f1]].sr+a[m[f2]].sl;
				
				Pic danni = izch(sum);
				if(m[f]!=0)
				{
					a[m[f]] = {a[m[f1]].sl,a[m[f2]].sr,a[m[f1]].br+a[m[f2]].br+danni.br};
					
				}
				else
				{
					D++;
					m[f]=D;
					a[m[f]] = {a[m[f1]].sl,a[m[f2]].sr,a[m[f1]].br+a[m[f2]].br+danni.br};
				}
				if(a[m[f]].sl.size()<3)
				{
					int dsum = sum.size();
					int g = min(dsum,3);
					a[m[f]].sl = sum.substr(0,g);
				}
				if(a[m[f]].sr.size()<3)
				{
					int dsum = sum.size();
					int g = min(dsum,3);
					a[m[f]].sr = sum.substr(dsum-g,g);
				}
				//cout<<a[m[f]].sl<<" "<<a[m[f]].sr<<endl;
			}
		}
		cout<<a[m[f]].br<<endl;
	}
	return 0;
}