CCF认证 201903-4 消息传递接口

#include <iostream>
#include <queue>
#include <list>
#include <unordered_set>
#include <cstring>
using namespace std;
int main(){
    //freopen("1.txt","r",stdin);
    ios::sync_with_stdio(false);
    int T,n;
    cin>>T>>n;
    cin.get();
    while(T--){
        list<pair<queue<int>,int>>process;//first成员是一个队列,存储每个进程的所有指令;second成员存储上一条执行的指令,初始化为INT_MAX
        unordered_set<int>commands;//存储每个进程正在执行的指令
        for(int i=0;i<n;i++){
            process.push_back({queue<int>(),INT_MAX});
            string str;
            getline(cin,str);            
            for(int j=0,k;j<str.length();j=k+1){//按空格键分割字符串,并用整数表示指令
                k=str.find(' ',j);
                if(k==string::npos) k=str.length();
                if(str[j]=='S'){
                    process.back().first.push(10000*i+stoi(str.substr(j+1,k-j-1)));
                }
                else{
                    process.back().first.push(-(stoi(str.substr(j+1,k-j-1))*10000+i));
                }                
            }            
        }
        bool flag=false;//flag标志是否所有进程指令都被堵塞
        while(!flag){//遍历完所有进程后发现所有进程均被堵塞,说明发生死锁
            flag=true;
            for(auto it=process.begin();it!=process.end();it++){//遍历所有进程
                if(commands.find(it->second)!=commands.end())//上一次执行的指令被堵塞了
                    continue;//进程也被堵塞,其他指令无法执行
                if((it->first).empty()){//所有指令均已执行完毕
                    it=process.erase(it);//将该进程删除
                    it--;
                    continue;
                }
                while(!(it->first).empty()){//进程还有指令要执行
                    int x=(it->first).front();//从队首弹出一条指令
                    (it->first).pop();
                    auto item=commands.find(-x);//查找其它进出中是否有正在执行的对应的指令
                    if(item!=commands.end()){//有对应的指令
                        commands.erase(item);//将对应的指令从commands中删除
                        flag=false;//并不是所有进程都被堵塞
                    }
                    else{//没有对应的指令
                        commands.insert(x);//将该指令插入到commands中
                        it->second=x;//更新上一次执行的指令为当前指令
                        break;
                    }
                }
            }
        }
        if(process.empty()) cout<<"0"<<endl;
        else cout<<"1"<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值