例题6-1 并行程序模拟(Concurrency Simulator, ACM/ICPC World Finals 1991, UVa210)

原题链接:https://vjudge.net/problem/UVA-210
分类:队列
备注:双端队列的应用

注意要点:当lock未解除时,下一次遇到lock,lock语句不执行直接将程序存入阻止队列然后走下一个程序。

代码如下:

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
int T, n, t1, t2, t3, t4, t5, Q;
int pos[30], pend[30], val[30];
string line[255];
int main(void) {
	scanf("%d", &T);
	int ju = 0;
	while (T--) {
		scanf("%d %d %d %d %d %d %d", &n, &t1, &t2, &t3, &t4, &t5, &Q);
		getchar();
		if (ju)printf("\n");
		else ju = 1;
		memset(val, 0, sizeof(val));
		int p = 1, locked = 0;
		deque<int>ready;
		queue<int>block;
		for (int i = 1; i <= n; i++) {
			pos[i] = p;
			while (getline(cin, line[p++])) 
				if (line[p - 1] == "end")break;
			pend[i] = p - 1;
			ready.push_back(i);
		}
		while (!ready.empty() || !block.empty()) {
			int now = ready.front(); ready.pop_front();
			int cost = 0, flag = 0;
			while (cost < Q) {
				int ha = pos[now];
				if (line[ha] == "end") {
					flag = 1; break;//结束跳出
				}
				else if (line[ha][1] == 'r') {
					printf("%d: %d\n", now, val[line[ha][6] - 'a']);
					cost += t2;
				}
				else if (line[ha][2] == 'c') {
					if (locked) {
						block.push(now); 
						flag = 1; break;//被锁跳出
					}
					locked = 1;
					cost += t3;
				}
				else if (line[ha][2] == 'l') {
					if (locked) locked = 0;
					if (!block.empty()) {
						ready.push_front(block.front());
						block.pop();
					}
					cost += t4;
				}
				else {
					sscanf(&line[ha].c_str()[4], "%d", &val[line[ha][0] - 'a']);
					cost += t1;
				}
				pos[now]++;
			}
			if(!flag)ready.push_back(now);
		}
	}
	return 0;
}
发布了104 篇原创文章 · 获赞 97 · 访问量 4515

猜你喜欢

转载自blog.csdn.net/TK_wang_/article/details/105338891