#include<cstdio>
#include<string>
#include<iostream>
#include<sstream>
#define max(a,b) ((a)>(b)?(a):(b));
using namespace std;
string tmp,t;
int F;
int Vis[256];
char bl, st, en;
inline string f(int k) {
F = 0;
int R = 0;
for(i=0;i<k;++i) {
getline(cin, tmp);
if (tmp[0] == 'F') {
sscanf(tmp.c_str(), "F %c %s", &bl, t.c_str());
if( ! ( isdigit ( t [ 0 ] ) &&
isdigit ( t [ t.size() - 1 ] )
)
++R;
if (Vis[bl])return "ERR";
}
}
if (R) {
stringstream Str;
Str << "O(n^" << R << ")";
return Str.str();
}
else return"O(1)";
}
int main(void) {
int q,T;
ios::sync_with_stdio(false);
cin >> q;
while (q--) {
string He;
cin >> T >> He;
tmp = f();
if (tmp == "ERR")printf("ERR\n");
else
if (tmp == He)printf("Yes\n");
else printf("No\n");
}
}