紫书上面的一道例题。
其实是一道很简单的模拟水题,但是,由于英语太渣,我看不懂题,于是乎,我手推了半个多小时的样例输出,才最终确定,lock真的只有一个改变程序运行顺序的作用。
剩下的,就是开一个双向队列ready,和一个普通队列block,按照题目的要求乱搞了。
#include <queue>
#include <iostream>
#include <string>
#include <cstdio>
#include <map>
#include <sstream>
#include <fstream>
using namespace std;
//ifstream cin;
//ofstream cout;
int main() {
// cin.open("//Users//pengao//Desktop//data.txt");
// cout.open("//Users//pengao//Desktop//out.txt");
int totCase;
// scanf("%d", &totCase);
cin >> totCase;
while (totCase--) {
queue<int> block; //block队列
deque<int> ready; //ready队列
map<string, string> values; //储存变量
vector<queue<string>> programs; //储存每个程序
int n;
int t[5]; //每个操作的时间
int quantem; //时间周期
bool lock = false;
// scanf("%d", &n);
cin >> n;
for (int i = 0; i < 5; i++)
// scanf("%d", &t[i]);
cin >> t[i];
// scanf("%d", &quantem);
cin >> quantem;
cin.get();
for (int i = 0; i < n; i++) {
string cmd;
queue<string> program; //储存一个程序
while (getline(cin, cmd) && cmd != "end") {
program.push(cmd);
}
program.push(cmd);
programs.push_back(program);
ready.push_back(i);
}
while (!ready.empty()) {
int current = ready.front();
int q = quantem;
bool blocked = false; //标记该程序是否需要加入ready(如果进入了blocked或者运行到 end,不需要加入)
ready.pop_front();
while (q > 0) {
string cmd = programs[current].front();
stringstream ss(cmd);
string commands[3];
int i = 0;
//对每条语句进行处理
while (ss >> commands[i]) {
i++;
}
if (commands[1] == "=") {
q -= t[0];
values[commands[0]] = commands[2];
}
else if (commands[0] == "print") {
q -= t[1];
if (!values.count(commands[1]))
values[commands[1]] = "0";
cout << current + 1 << ": " << values[commands[1]] << endl;
}
else if (commands[0] == "lock") {
q -= t[2];
if (lock) {
block.push(current);
blocked = true;
break;
}
else
lock = true;
}
else if (commands[0] == "unlock") {
lock = false;
q -= t[3];
if (!block.empty()) {
int id = block.front();
block.pop();
ready.push_front(id);
}
}
else if (commands[0] == "end") {
blocked = true;
break;
}
programs[current].pop(); //如果lock,则lock依然在程序里面,即下次运行时先从lock开始运行
}
if (!blocked)
ready.push_back(current);
}
if (totCase)
cout << endl;
}
return 0;
}
/*
之前上传的代码复制错了,现在已经更正过来了
1.在每次循环前没有初始化,正确的代码直接把容器的定义放在了每次循环里面
2.判断时间是否用完应该是while (q > 0),之前复制的时候那一版是while (q)
/*