例题6-1:并行程序模拟
题意:
给定n个程序,每种程序有五种操作,分别为 var = constant(赋值),print var (打印), lock, unlock,end 变量用小写字母表示,初始化为0,为程序所公有(一个程序里对某个变量修改可以会影响其他程序里的这个变量),常数小于100(也就是说最多两位数)。每个时刻都只能有一个程序处于运行状态,其他的都在等待,上述五种操作用时分别是t1, t2, t3, t4, t5。运行中的程序每次最多能运行q个时间,当q个时间被用完后,它会被放在等待队列的尾部,然后再从首部取出一个程序运行,初始等待队列按输入顺序,
但是lock和unlock会改变顺序,它们总是成对出现,不会出现嵌套。如果某个程序已经执行了lock,后面还有程序执行lock,那么这个程序就会马上被放到一个阻止队列的尾部(当然如果运行时间还没用完也就浪费了)。当unlock结束后,阻止队列中的第一个程序进入等待队列的首部。问你程序的运行结果是什么,输出格式是第几个程序加冒号加空格加结果,两个相连的数据用空行隔开。
#include<iostream>
#include<string>
#include<string.h>
#include<cstdio>
#include<deque>
#include<vector>
#include<queue>
using namespace std;
const int MAXN=1005;
bool lock;
deque<int>qr;
queue<int>qw;
vector<string> sta[MAXN];
int var[26],p[MAXN],t[MAXN];
int Q;
void run(int i)
{
int rt=Q,v;
string cur;
while(rt>0){
cur=sta[i][p[i]];
if(cur[2]=='='){
rt-=t[0];
v=cur[4]-'0';
if(cur.size()==6)v=v*10+cur[5]-'0';
var[cur[0]-'a']=v;
}
else if(cur[2]=='i'){
rt-=t[1];
printf("%d: %d\n",i,var[cur[6]-'a']);
}
else if(cur[2]=='c'){
rt-=t[2];
if(lock){
qw.push(i);
return;
}
else lock=true;
}
else if(cur[2]=='l'){
lock=false;
rt-=t[3];
if(!qw.empty()){
v=qw.front();
qw.pop();
qr.push_front(v);
}
}
else return;
++p[i];
}
qr.push_back(i);
}
int main()
{
int cas;
scanf("%d",&cas);
while(cas--){
int n;
scanf("%d",&n);
for(int i=0;i<5;i++)
scanf("%d",&t[i]);
scanf("%d",&Q);
string s;
for(int i=1;i<=n;i++){
sta[i].clear();
while(getline(cin,s)){
if(s=="")continue;
sta[i].push_back(s);
if(sta[i].back()=="end")break;
}
qr.push_back(i);
}
memset(p,0,sizeof(p));
memset(var,0,sizeof(var));
while(!qr.empty()){
int cur=qr.front();
qr.pop_front();
run(cur);
}
if(cas) printf("\n");
}
return 0;
}