Uva210并行程序模拟
开始没有弄懂题意,参考大佬的代码写的,思路很清晰,但是在vistual judge上面发现是错的,怀疑可能是输入数据的问题,如果有观者知道原因,还请告知,不胜感激
题目大意
题意:给定n个程序,每种程序有五种操作,分别为 var = constant(赋值),print var (打印), lock, unlock,end
变量用小写字母表示,初始化为0,为程序所公有(一个程序里对某个变量修改可以会影响其他程序里的这个变量),
常数小于100(也就是说最多两位数)。
每个时刻都只能有一个程序处于运行状态,其他的都在等待,上述五种操作用时分别是t1, t2, t3, t4, t5。运行中的程序,
每次最多能运行q个时间,当q个时间被用完后,它会被放在等待队列的尾部,然后再从首部取出一个程序运行,初始等待队列按输入顺序,
但是lock和unlock会改变顺序,它们总是成对出现,不会出现嵌套。如果某个程序已经执行了lock,后面还有程序执行lock,
那么这个程序就会马上被放到一个阻止队列的尾部(当然如果运行时间还没用完也就浪费了)。当unlock结束后,阻止队列中的第一个程序进入等待队列的首部。
问你程序的运行结果是什么,输出格式是第几个程序加冒号加空格加结果,两个相连的数据用空行隔开。(详见白书第二版p139)
测试数据
1
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 = z5
a = 17
print a
print b
lock
b = 21
print b
unlock
print b
end
伪代码
伪代码
while(等待队列里还有程序)
{
while(程序还有配额)
{
if(执行完没有配额了) 放到队列队列末尾
if(程序是lock)
{
if(现在是锁定状态) 放到阻塞队列
if(现在不是锁定状态) 状态改为锁定状态
}
减少配额;
if(赋值) 进行赋值运算
if(取值) 进行取值运算
if(unlock)
{
解除锁定状态
if(阻塞队列不为空) 讲阻塞队列队首放入等待队列队首
}
}
}
源码
#include <iostream>
#include <deque>
#include<vector>
#include<cstdio>
#include <string>
#include <cstring>
#include<queue>
#include <sstream>
using namespace std;
const int Maxn=1005;
struct Program
{
int number;//编号
queue<string> code;//若干条语句
Program(int number):number(number){};//初始化列表,多个字段需要初始化只需要用,分隔
/*
员初始化列表不是单纯的初始化,他是编译器在构造函数所有自写代码之前插入
编译器做的优化,不会有临时变量产生
并且有几种情况,必须使用成员初始化列表,不能自写初始化
1 没有无参构造函数的成员对象
2 const成员变量或引用
3 子类初始化父类的私有成员
*/
};
int main()
{
int T;
cin>>T;
while(T--)
{
int n,t1,t2,t3,t4,t5,q;
int ch[30]; //变量
int toTime[130]; //将命令转换为时间
deque<Program> wait; //等待队列
queue<Program> stop; //阻止队列
bool isLock = false; //是否处于lock状态
// memset(ch,0,sizeof(ch));
cin>>n>>t1>>t2>>t3>>t4>>t5>>q;
getchar(); //处理末尾的换行符号
//直接用字符串中的第三个字符作为作为下标来处理,一大亮点,但是如果出现a=3这种中间没有空格符的错的输入数据,就会导致出错
toTime['='] = t1;
toTime['i'] = t2;
toTime['c'] = t3;
toTime['l'] = t4;
toTime['d'] = t5;
for(int i=1;i<=n;i++)//输入
{
string s;
Program program(i);
while(1)
{
getline(cin,s);
program.code.push(s);//code是一个结构体
if(s=="end")
break;
}
wait.push_back(program);
}
//模拟运行
while(!wait.empty())
{
//取等待队列队首程序
Program program = wait.front();
wait.pop_front();
int t=q;
//模拟运行
while(!program.code.empty())
{
string s = program.code.front();
//时间不够执行这一条语句,退出当前程序
if(t<=0)
{
wait.push_back(program);
break;
}
//如果当前是Lock语句
if(s[2]=='c')
{
if(isLock)//如果当前是lock状态
{
stop.push(program);
break;
}
else//否则进入锁定状态
{
isLock = true;
}
}
//执行这条语句,并减少当前时间配额
t-=toTime[s[2]];
program.code.pop();
if(s[2]=='l')
{
isLock = false;
if(!stop.empty())
{
wait.push_front(stop.front());
stop.pop();
}
}
if(s[2]=='=')
{
char c;
string t;
int num;
stringstream ss(s);
ss>>c>>t>>num;
// cout<<"test:"<<c<<' '<<t<<' '<<num<<endl;
// cout<<num<<endl;
// cout<<"test:"<<c<<' '<<num<<endl;
ch[c-'a'] = num;
}
if(s[2]=='i')
{
cout<<program.number<<": "<<ch[s[6]-'a']<<endl;
}
if(s[2]=='d')
break;
}
}
if(T) cout<<endl;
}
return 0;
}