#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
#include <unordered_map>
#include<numeric>
#include<chrono>
#include<random>
//mt19937 rng((unsigned int)chrono::steady_clock::now().time_since_epoch().count());

//#include"testlib.h"
#define endl '\n'
#define all(v) v.begin(),v.end()
#define allr(s) s.rbegin(),s.rend()
#define RT(s) return cout<<s,0
#define sz(s)    (int)(s.size())
//#define PI acos(-1)
#define EPS 1e-8
#define watch(x) cout << (#x)<<" = "<<x<<endl
#define mk(x, y) make_pair(x, y)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
//int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 };
//int dx[] = { 0, 0, 1, -1, 1, -1, 1, -1 };
void file() {
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
#else
	//freopen("math.in", "r", stdin);
	//freopen("out.txt", "w", stdout);
#endif
}

void fast() {
	std::ios_base::sync_with_stdio(0);
	cin.tie(NULL);
}
const string haha = "haha";
inline string get_first(string& str) {
	string ret = "";
	for (int i = 0; i < min(3, sz(str)); i++)
		ret.push_back(str[i]);
	return ret;
}
inline string get_last(string& str) {
	string ret = "";
	for (int i = max(0, sz(str) - 3); i < sz(str); i++)
		ret.push_back(str[i]);
	return ret;
}
inline int get_cnt(string& str) {
	int ret = 0;
	for (int i = 0; i + sz(haha) - 1 < sz(str); i++) {
		bool ok = true;
		for (int j = 0; j < sz(haha); j++)
			if (str[i + j] != haha[j]) {
				ok = false;
				break;
			}
		if (ok) ret++;
	}
	return ret;
}
struct SS {
	ll cnt;
	string l, r;
	SS(string& str) {
		cnt = get_cnt(str);
		l = get_first(str);
		r = get_last(str);
	}
	SS() {

	}
};
SS merge(SS l, SS r) {
	SS ret;
	string tmp = l.r + r.l;
	ret.cnt = l.cnt + r.cnt + get_cnt(tmp);
	ret.l = l.l;
	if (sz(ret.l) < 3)
		ret.l = get_first(tmp);
	ret.r = r.r;
	if (sz(ret.r) < 3)
		ret.r = get_last(tmp);
	return ret;
}
void test_case() {
	int n; cin >> n;
	map<string, SS> mp;
	string varName;
	for (int i = 0; i < n; i++) {
		cin >> varName;
		char ch; cin >> ch;
		if (ch == '=') {
			string a, b;
			cin >> a >> ch >> b;
			mp[varName] = merge(mp[a], mp[b]);
			continue;
		}
		cin >> ch;
		string str; cin >> str;
		mp[varName] = SS(str);
	}
	cout << mp[varName].cnt << endl;
}
int main() {
	file();
	fast();
	int t; cin >> t;
	while (t--) {
		test_case();
	}
	return 0;
}