210:Concurrency Simulator
没看清楚题意考虑复杂了。。我以为是如果剩下的时间不够一条指令执行完的话这段时间还是算的,搞的还挺麻烦的,比如这条指令需要10秒,剩下5秒,那么下次执行的时候只需5秒就行了。其实不是的,题目中说:
Any instruction currently beingexecuted when the time quantum expires will be allowed to complete.
意思就是当前执行的程序无论时间到了没有都要执行完。所以只要剩余时间大于0就可以执行下一条指令,而不用事先判断剩余时间是否大于该条指令的执行时间。
还出了一些特别白痴的bug,cn 写成 i,if 语句少写了大括号。。。
version 1(280ms):
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 5;
int T,n,Q,t[5];
string key[] = {"=","print","unlock","lock","end"};
int main(){
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
string s;
cin>>T;
while(T--){
getline(cin,s);
cin>>n;
map<char,int>vars;
vector<string>cmds[maxn];
int loc[maxn]; //记录每段程序执行到哪条语句
memset(loc,0,sizeof(loc));
queue<int>sq;
deque<int>q;
for(int i = 0;i < 5;i++) scanf("%d",&t[i]);
swap(t[2],t[3]);
scanf("%d\n",&Q);
for(int i = 0;i < n;i++){
while(getline(cin,s) && s != "end") cmds[i].push_back(s);
q.push_back(i);
}
int lock = 0;
while(!q.empty()){
int cn = q.front(); q.pop_front();
vector<string>cmd = cmds[cn];
int i = loc[cn],rt = Q; //rest time
int mark = 1;
for(;i < cmd.size() && rt > 0;i++){
s = cmd[i];
int j = 0;
while(s.find(key[j]) == string::npos) j++;
if(s.find('=') != string::npos){
vars[s[0]] = stoi(s.substr(s.find('=')+1));
}else if(s.find("print") != string::npos){
printf("%d: %d\n",cn+1,vars[s[s.find(' ')+1]]);
}else if(s.find("unlock") != string::npos){
if(!sq.empty()){
q.push_front(sq.front()); sq.pop();
}
lock = 0;
}
else if(s.find("lock") != string::npos){
if(lock){
sq.push(cn);
mark = 0;
break;
}
else lock = 1;
}
loc[cn]++;
rt -= t[j];
}
if(mark && i < cmd.size()) q.push_back(cn);
}
if(T) putchar('\n');
}
return 0;
}
version 2(180ms):
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 5;
int T,n,Q,t[5];
int main(){
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
string s;
cin>>T;
while(T--){
getline(cin,s);
cin>>n;
char vars[26];
vector<string>cmds[maxn];
int loc[maxn]; //记录每段程序执行到哪条语句
memset(loc,0,sizeof(loc));
memset(vars,0,sizeof(vars));
queue<int>sq;
deque<int>q;
for(int i = 0;i < 5;i++) scanf("%d",&t[i]);
swap(t[2],t[3]);
scanf("%d\n",&Q);
for(int i = 0;i < n;i++){
while(getline(cin,s) && s != "end") cmds[i].push_back(s);
q.push_back(i);
}
int lock = 0;
while(!q.empty()){
int cn = q.front(); q.pop_front();
vector<string>cmd = cmds[cn];
int mark = 1,rt = Q; //rest time
while(loc[cn] < cmd.size() && rt > 0){
s = cmd[loc[cn]];
if(s[2] == '='){
vars[s[0] - 'a'] = stoi(s.substr(4));
rt -= t[0];
}else if(s[0] == 'p'){
printf("%d: %d\n",cn+1,vars[s[6] - 'a']);
rt -= t[1];
}else if(s[0] == 'u'){
if(!sq.empty()){
q.push_front(sq.front()); sq.pop();
}
lock = 0;
rt -= t[2];
}
else if(s[0] == 'l'){
if(lock){
sq.push(cn);
mark = 0;
break;
}
else{ lock = 1;rt -= t[3]; }
}
loc[cn]++;
}
if(mark && loc[cn] < cmd.size()) q.push_back(cn);
}
if(T) putchar('\n');
}
return 0;
}
Email:JingwangLi@outlook.com