您的位置:首页 > 其它

UVa 210 Concurrency Simulator

2015-12-03 17:17 316 查看
    在做这题的过程中出现了两个问题。

    假如s是一个字符输入流,从s中得到一个整数,代码可能如下:

int a;
s>>a;

    但需注意的是,s中整数字符前若有别的非空白字符,则该字符会被转换成一个整数赋给a,而且这个整数可能为任意值。所以应该改成如下写法,跳过那个字符:

char ch;
int a;
s>>ch>>a;

    另外,一定要注意输出格式。题目说两个case间要输出一个空行,但最后一个case后是不应该有空行的,我因此wrong answer两次,看到别人的代码注意了这点才反应过来。下面给出源代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <deque>
#include <queue>
#include <vector>
#include <map>
using namespace std;
struct program
{
program() = default;
program(int a, const deque<string> &q) :ID(a), codes(q) {}
program(const program& p)
{
ID = p.ID;
codes = p.codes;
}
program &operator=(const program& right) { ID = right.ID; codes = right.codes; return *this; }
int ID;
deque<string> codes;
//int executeNext() {}
bool empty() { return codes.empty(); }
};
deque<program> waiting; // 每个case过后要把这几个全局变量clear
deque<program> blocked;
bool locked;
int period;
map<char, int> variations; //变量→值
vector<int> stepTime;
void initialVars() //添加所有的变量,将所有的变量赋为0
{
for (char ch = 'a'; ch <= 'z'; ++ch)
variations[ch] = 0;
}
void recoverVars()
{
waiting.clear();
blocked.clear();
locked = false;
initialVars();
stepTime.clear();
}
void run()
{
while (!waiting.empty())
{
//cout << "fuck";
program current = waiting[0];
int usedTime; //每一步耗费的时间
int flag = false; //current是否被放到了阻止队列
for (int time = period; time > 0 && !current.empty(); time -= usedTime)
{
string statement = current.codes[0];
istringstream line(statement);
if (statement.find('=') != std::string::npos) //如果是赋值语句
{
char left,ch;
int right;
line >> left >>ch>> right;
variations[left] = right;
usedTime = stepTime[0];
}
else if (statement[0] == 'p')
{
string temp;
char ch;
line >> temp >> ch;
cout << current.ID << ": " << variations[ch] << endl;
usedTime = stepTime[1];
}
else if (statement == "lock")
{
if (locked) //如果已经被锁了
{
blocked.push_back(current); //放到阻止队列
flag = true;
break;
}
locked = true;
usedTime = stepTime[2];
}
else if (statement == "unlock")
{
locked = false;
if (!blocked.empty()) //如果阻止队列非空,则将队首的程序移到等待队列
{
program temp = blocked[0];
blocked.pop_front();
auto it = waiting.begin();
++it;
waiting.insert(it, temp);
}
usedTime = stepTime[3];
}
else
{
usedTime = stepTime[4];
}
current.codes.pop_front();
}
waiting.pop_front(); //从队首移走
if (!current.empty() && !flag)
waiting.push_back(current);
}
}
int main()
{
int cases;
string s;
cin >> cases;
getline(cin,s);
getline(cin, s);
for (int i = 1; i <= cases; ++i)
{
recoverVars();
int num;
cin >> num;
for (int j = 1; j <= 5; ++j)
{
int temp;
cin >> temp;
stepTime.push_back(temp);
}
cin >> period;
getline(cin, s);
for (int k = 1; k <= num; ++k)
{
deque<string> temp;
while (getline(cin, s) && s != "end")
temp.push_back(s);
temp.push_back(s);
program p(k, temp);
waiting.push_back(p);
}
run();
if (i != cases)
{
cout << endl;
getline(cin, s);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UVa 算法题