#include<iostream>
#include<cstdio>
#include<string>
#include<map>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<cstring>
#include<stack>
using namespace std;
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
typedef set<int> Set;
map<Set,int> set2int;
vector<Set> v;
int getid(Set t)
{
if(set2int.count(t))
return set2int[t];
v.push_back(t);
return set2int[t]=v.size()-1;
}
int main()
{
int t,step;
cin>>t;
while(t)
{
stack<int> st;
int i;
cin>>step;
for(i=0;i<step;i++)
{
string s;
cin>>s;
if(s[0]=='P')
{
Set temp;
int id=getid(temp);
st.push(id);
}
else if(s[0]=='D')
{
int id=st.top();
st.push(id);
}
else if(s[0]=='U')
{
Set x;
int id1=st.top();
st.pop();
int id2=st.top();
st.pop();
set_union(ALL(v[id1]),ALL(v[id2]),INS(x));
st.push(getid(x));
}
else if(s[0]=='I')
{
Set x;
int id1=st.top();
st.pop();
int id2=st.top();
st.pop();
set_intersection(ALL(v[id1]),ALL(v[id2]),INS(x));
st.push(getid(x));
}
else if(s[0]=='A')
{
Set x;
int id1=st.top();
st.pop();
int id2=st.top();
st.pop();
x=v[id2];
x.insert(getid(v[id1]));
st.push(getid(x));
}
cout<<v[st.top()].size()<<endl;
}
cout<<"***"<<endl;
t--;
}
return 0;
}