#include <iostream>
#include <queue>
#include <list>
#include <unordered_set>
#include <cstring>
using namespace std;
int main(){
//freopen("1.txt","r",stdin);
ios::sync_with_stdio(false);
int T,n;
cin>>T>>n;
cin.get();
while(T--){
list<pair<queue<int>,int>>process;//first成员是一个队列,存储每个进程的所有指令;second成员存储上一条执行的指令,初始化为INT_MAX
unordered_set<int>commands;//存储每个进程正在执行的指令
for(int i=0;i<n;i++){
process.push_back({queue<int>(),INT_MAX});
string str;
getline(cin,str);
for(int j=0,k;j<str.length();j=k+1){//按空格键分割字符串,并用整数表示指令
k=str.find(' ',j);
if(k==string::npos) k=str.length();
if(str[j]=='S'){
process.back().first.push(10000*i+stoi(str.substr(j+1,k-j-1)));
}
else{
process.back().first.push(-(stoi(str.substr(j+1,k-j-1))*10000+i));
}
}
}
bool flag=false;//flag标志是否所有进程指令都被堵塞
while(!flag){//遍历完所有进程后发现所有进程均被堵塞,说明发生死锁
flag=true;
for(auto it=process.begin();it!=process.end();it++){//遍历所有进程
if(commands.find(it->second)!=commands.end())//上一次执行的指令被堵塞了
continue;//进程也被堵塞,其他指令无法执行
if((it->first).empty()){//所有指令均已执行完毕
it=process.erase(it);//将该进程删除
it--;
continue;
}
while(!(it->first).empty()){//进程还有指令要执行
int x=(it->first).front();//从队首弹出一条指令
(it->first).pop();
auto item=commands.find(-x);//查找其它进出中是否有正在执行的对应的指令
if(item!=commands.end()){//有对应的指令
commands.erase(item);//将对应的指令从commands中删除
flag=false;//并不是所有进程都被堵塞
}
else{//没有对应的指令
commands.insert(x);//将该指令插入到commands中
it->second=x;//更新上一次执行的指令为当前指令
break;
}
}
}
}
if(process.empty()) cout<<"0"<<endl;
else cout<<"1"<<endl;
}
return 0;
}