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

void hhh() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
}

int check( string &s) {
	// chu cai dau tien uppercase
	//i a m
	// m a i
	if( islower(s[0])) return 0 ;
	transform(s.begin(), s.end(), s.begin(), ::tolower);
	string m1 = "mai";
	string m2 = "iam";
	int idex1 = 0 ;
	int idex2 = 0 ;

	for( int i = 0 ; i < s.size() ; i++ ) {
		if( s[i] == m1[idex1]) {

			++idex1;
		}
		if( s[i] == m2[idex2]) {

			++idex2;
		}
		if( idex1 == 3 || idex2 == 3) return 1;
	}
	return 0;
}
int main() {
	hhh();
	int t;
	cin >> t;
	while (t--) {
		cin.ignore();
		string test;
		int cnt = 0 ;
		getline( cin, test);

		string word;

		stringstream ss(test);

		while( ss >> word) {
			if( check(word)) {
				++cnt;
			}
		}
		cout << cnt<< '\n';
	}
}