#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <sstream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 10017;
#define pii pair<int, int>
int n, tot;
vector<int> G[MAXN];
vector<pii> task[MAXN];
bool vis[500000];
int deg[500000];
int dict[MAXN][100];
int work(){
//init
tot = 0;
memset(vis, 0, sizeof(vis));
memset(deg, 0, sizeof(deg));
memset(dict, 0, sizeof(dict));
for(int i = 0; i < n; i++)
task[i].clear();
//read
for(int i = 0; i < n; i++){
string line;
getline(cin, line);
stringstream lin(line);
char ch;
int num;
while(lin >> ch >> num){
if(ch == 'S')
task[i].push_back(pii(1, num));
else
task[i].push_back(pii(0, num));
}
}
//hash to one node
for(int i = 0; i < n; i++){
for(int j = 0; j < task[i].size(); j++){
if(dict[i][j]) continue;
int type = task[i][j].first;
int to = task[i][j].second;
int index = -1;
for(int k = 0; k < task[to].size(); k++){
if(task[to][k].second == i && (task[to][k].first ^ type))
index = k;
}
if(index == -1)
return 1;
dict[i][j] = dict[to][index] = ++tot;
}
}
//clear graph
for(int i = 0; i <= tot; i++)
G[i].clear();
//build gragh
for(int i = 0; i < n; i++){
for(int j = 0; j < task[i].size() - 1; j++){
int node = dict[i][j];
int nxt = dict[i][j+1];
G[node].push_back(nxt);
deg[nxt] ++;
}
}
//sort
queue<int> q;
for(int i = 1; i <= tot; i++)
if(deg[i] == 0)
q.push(i);
while(!q.empty()){
int f = q.front();
q.pop();
for(auto nxt : G[f]){
deg[nxt]--;
if(deg[nxt] == 0)
q.push(nxt);
}
}
//judge
for(int i = 1; i <= tot; i++)
if(deg[i])
return 1;
return 0;
}
int main(){
int t;
string line;
getline(cin, line);
stringstream lin(line);
lin >> t >> n;
while(t--)
cout << work() << endl;
}
来源:https://blog.csdn.net/weixin_43918760/article/details/100862320