题目链接:http://118.190.20.162/view.page?gpid=T86
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <memory.h>
using namespace std;
int T,n;
struct progress{
int no;
char op;
};
const int maxn=10005;
vector<progress> g[maxn];
bool check(){
for(int i=0;i<n;i++){
if(g[i].size()!=0){
return false;
}
}
return true;
}
int run(int cur){
int dest=g[cur][0].no;
if(g[dest].size()==0) return 0; //目的进程为空则不能消除
if(g[cur][0].op!=g[dest][0].op&&g[dest][0].no==cur){ //可以对应进行消除
g[cur].erase(g[cur].begin());
g[dest].erase(g[dest].begin());
return 1;
}
return 0;
}
int main() {
cin>>T>>n;
getchar();
while(T--){
string str;
for(int i=0;i<n;i++){
g[i].clear();
}
for(int i=0;i<n;i++){
getline(cin,str);
string b;
progress p;
for(int j=0;j<str.size();j++){
if(str[j]==' '){
p.op=b[0];
p.no=0;
for(int k=1;k<b.size();k++){
p.no=p.no*10+(b[k]-'0');
}
g[i].push_back(p);
b="";
}
else
{
b+=str[j];
}
}
p.op=b[0];
p.no=0;
for(int k=1;k<b.size();k++){
p.no=p.no*10+(b[k]-'0');
}
g[i].push_back(p);
}
bool flag;
while(1){
int num=0; //消除的进程对数
for(int i=0;i<n;i++){
if(g[i].size()!=0){
if(run(i)){
num++;
}
}
}
if(check()){ //全部消除成功
flag=false;
break;
}
if(num>0){ //消除了,继续循环
continue;
} else if(num==0){ //一个也没消除,发生死锁
flag=true;
break;
}
}
cout<<flag<<endl;
}
return 0;
}