本题思路
思路较简单,用n个队列模拟n个进程;
每轮循环考虑n个进程的当前指令,若两个进程的R、S相匹配,则可以出队;
当一轮中没有匹配的进程时循环结束;
最后查询所有队列,若都为空则不存在死锁;
满分代码(C++11)
#pragma GCC optimize(2)
#pragma GCC optimize(3, "Ofast", "inline")
#include <bits/stdc++.h>
using namespace std;
struct Ins
{
bool RS;
int num;
Ins(bool a, int b) : RS(a), num(b) {}
bool operator== (const Ins& b)
{
return RS == b.RS && num == b.num;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T, n;
cin >> T >> n;
cin.get();
while (T--)
{
vector<queue<Ins>> process;
process.assign(n, queue<Ins>());
string line, ins;
for (int i = 0; i < n; ++i)
{
getline(cin, line);
stringstream ss(line);
while (ss >> ins)
{
bool RS = ins[0] == 'R' ? 0 : 1;
int num = stoi(ins.substr(1));
process[i].emplace(RS, num);
}
}
bool flag = true;
while (flag)
{
flag = false;
for (int i = 0; i < n; ++i)
{
if (process[i].empty())
continue;
Ins ins = process[i].front();
Ins expected_ins(!ins.RS, i);
int target = ins.num;
if (!process[target].empty() && process[target].front() == expected_ins)
{
flag = true;
process[i].pop();
process[target].pop();
}
}
}
flag = true;
for (int i = 0; i < n; ++i)
{
if (!process[i].empty())
{
flag = false;
break;
}
}
cout << (flag ? 0 : 1) << "\n";
}
return 0;
}
如果对您有帮助记得点个赞哟~