210 - Concurrency Simulator

欢迎folk或者star我的repo:https://github.com/guopeiming/algorithm-training,每天更新一道oj入门紫皮书上的题目或者oj、LeetCode,持续更新中

注意读题,每次block队列中第一个进入ready,然后重新执行lock语句!!!210-ConcurrencySimulator

#include <stdio.h>
#include <string.h>
#include <string>
#include <queue>
#include <stdlib.h>
using namespace std;

struct Process{
    int instIdx;
    char inst[30][15];
    Process(): instIdx(0){};
};

int data[30], insTime[5], n, quantum, flag;
Process pros[50];
deque<int> redy;
queue<int> block;

void execIns();

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        memset(data, 0, sizeof(data));
        memset(pros, 0, sizeof(pros));
        flag = 0;
        scanf("%d", &n);
        for(int i = 0; i < 5; ++i){
            scanf("%d", insTime+i);
        }
        scanf("%d", &quantum);
        getchar();
        for(int i = 0; i < n; ++i){
            int j = 0;
            while(1){
                scanf("%[^\n]", pros[i].inst[j]);
                getchar();
                if(!strcmp(pros[i].inst[j], "end")){
                    break;
                }
                j++;
            }
            redy.push_back(i);
        }
        while(!redy.empty()){
            execIns();
        }
        printf("%s", t==0?"":"\n");
    }
}

void execIns(){
    int p = redy.front(), time = quantum;
    redy.pop_front();
    char* ins;
    while(time > 0){
        ins = pros[p].inst[pros[p].instIdx];
        pros[p].instIdx++;
        if(ins[2] == '='){
            char * tempp;
            long temp = strtol(ins + 4, &tempp, 10);
            data[ins[0] - 'a'] = (int)temp;
            //data[ins[0] - 'a'] = ins[4] - '0';
            time -= insTime[0];
        }else if(ins[2] == 'i'){
            printf("%d: %d\n", p+1, data[ins[6] - 'a']);
            time -= insTime[1];
        }else if(ins[2] == 'c'){
            if(!flag){
                flag = 1;
            }else{
                pros[p].instIdx--;
                block.push(p);
                return;
            }
            time -= insTime[2];
        }else if(ins[2] == 'l'){
            flag = 0;
            if(!block.empty()){
                int temp = block.front();
                block.pop();
                redy.push_front(temp);
            }
            time -= insTime[3];
        }else if(ins[2] == 'd'){
            return;
        }
    }
    redy.push_back(p);
}

// Sample Input
// 3 1 1 1 1 1 1
// a = 4
// print a
// lock
// b = 9
// print b
// unlock
// print b
// end
// a = 3
// print a
// lock
// b = 8
// print b
// unlock
// print b
// end
// b = 5
// a = 17
// print a
// print b
// lock
// b = 21
// print b
// unlock
// print b
// end

// Sample Output
// 1: 3
// 2: 3
// 3: 17
// 3: 9
// 1: 9
// 1: 9
// 2: 8
// 2: 8
// 3: 21
// 3: 21

//队列的使用以及模拟题水题
posted @ 2019-09-21 09:44  回溯法  阅读(171)  评论(0编辑  收藏  举报