【CCF 201903-4】消息传递接口(队列)

本题思路

思路较简单,用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;
}

如果对您有帮助记得点个赞哟~

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值