#include<bits/stdc++.h>
using namespace std;
struct Tool{
string name;//器件名
int onum=0;//入度
vector<int> in;//来自标准输入
vector<int> oin;//来自其他器件输出的输入
vector<int> outdegree;//输出到的器件
};
int Q,M,N,flag;//flag为0时表示成环
void process(vector<int>&Out,vector<int>&In,Tool op,int index);
void topo(vector<Tool>& a,vector<int>& ord);
main()
{
ios::sync_with_stdio(0);//读入优化
cin >> Q;
while(Q--)
{
flag = 1;
cin >> M >> N;
vector<Tool> a;
vector<int> ord;//存拓扑排序结果
vector<int> In;//外部输入
vector<int> Out;//输出
vector<vector<int>> ans;//存输出答案
a.resize(N);
Out.resize(N);
In.resize(M);
for (int i = 0; i < N;i++)
{
string name;
int k;
string in;
cin >> name >> k;
a[i].name = name;
for (int j = 0; j < k;j++)
{
cin >> in;
if(in[0]=='I')
{
in = in.substr(1);
int t = stoi(in)-1;
a[i].in.push_back(t);
}
else
{
in = in.substr(1);
int t = stoi(in)-1;
a[t].outdegree.push_back(i);
a[i].oin.push_back(t);
a[i].onum++;
}
}
}
topo(a,ord);
int S;
cin >> S;
for (int i = 0; i < S; i++)
{
if (flag&&ord.size()<size_t(N))
{
cout << "LOOP" << endl;
flag=0;
}
for (int j = 0; j < M; j++)
{
cin >> In[j];
}
for (auto j : ord)
{
process(Out,In,a[j], j);
}
ans.push_back(Out);
}
for (int i = 0; i < S;i++)
{
int n;
cin >> n;
for (int j = 0; j < n;j++)
{
int num;
cin >> num;
if(flag)
cout << ans[i][num-1] << " ";
}
if(flag)
cout << endl;
}
}
}
void process(vector<int>&Out,vector<int>&In,Tool op,int index)
{
if(op.name=="NOT")
{
if(!op.in.empty())
{
Out[index] = 1-In[op.in[0]];
}
else
{
Out[index] = 1-Out[op.oin[0]];
}
}
else if(op.name=="AND")
{
Out[index] = 1;
for(auto i:op.in)
{
Out[index] &= In[i];
}
for(auto i:op.oin)
{
Out[index] &= Out[i];
}
}
else if(op.name=="OR")
{
Out[index] = 0;
for(auto i:op.in)
{
Out[index] |= In[i];
}
for(auto i:op.oin)
{
Out[index] |= Out[i];
}
}
else if(op.name=="XOR")
{
Out[index] = 0;
for(auto i:op.in)
{
Out[index] ^= In[i];
}
for(auto i:op.oin)
{
Out[index] ^= Out[i];
}
}
else if(op.name=="NAND")
{
Out[index] = 1;
for(auto i:op.in)
{
Out[index] &= In[i];
}
for(auto i:op.oin)
{
Out[index] &= Out[i];
}
Out[index] = 1 - Out[index];
}
else if(op.name=="NOR")
{
Out[index] = 0;
for(auto i:op.in)
{
Out[index] |= In[i];
}
for(auto i:op.oin)
{
Out[index] |= Out[i];
}
Out[index] = 1 - Out[index];
}
}
void topo(vector<Tool>& a,vector<int>& ord)
{
queue<int> q;
for (int i = 0; i < N;i++)
{
if(!a[i].onum)
{
q.push(i);
ord.push_back(i);
}
}
while(!q.empty())
{
int top = q.front();
q.pop();
ord.push_back(top);
for(auto i:a[top].outdegree)
{
a[i].onum--;
if(!a[i].onum)
{
q.push(i);
}
}
}
}
CCF CSP 点亮数字人生
最新推荐文章于 2024-03-23 14:28:43 发布