1、并行程序模拟(双端队列)

题意:输入n,表示有n个程序运行,有5个操作各自所需要的时间,还有每个程序运行一次的限制时间Q。输出程序打印结果

要点:当已经有程序lock时, 其他程序不能lock,反而被挂起,当lock的程序unlock后,被挂起的程序才被一个个取出运行

Sample Input

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 = 5
a = 17
print a
print b
lock
b = 21
print b
unlock
print b
end

Sample Output

1: 3
2: 3
3: 17
3: 9
1: 9
1: 9
2: 8
2: 8
3: 21
3:21

code

#include<iostream>
#include<string>
#include<string.h>
#include<deque>
#include<vector>
#include<queue>

const int MAXN = 1024;
using namespace std;
deque<int> qr;              //queue read
queue<int>qw;               //queue wait
vector<string> sta[MAXN];   //每个程序一个vector
int var[26], p[MAXN];		//每个字母一个数组元素
int t[6];
int Q;
bool lock;

void run(int i) {
	int rt = Q;
	string cur;
	while (rt > 0) {
		cur = sta[i][p[i]]; // p[i] 是i号程序的计数器,记录指令执行的位置。
		if (cur[2] == '=')
		{
			rt -= t[0];
			int temp = cur[4] - '0';
			if (cur.size() == 6)    // 常数有一位有两位
				temp = 10 * temp + cur[5] - '0';
			var[cur[0] - 'a'] = temp;
		}
		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;          //茅坑已经被lock了,不能执行指令,p[i]不变
			}
			else
				lock = true;
		}
		else if (cur[2] == 'l') {
			lock = false;
			rt -= t[3];
			if (!qw.empty()) {
				qr.push_front(qw.front());
				qw.pop();
			}
		}
		else
			return;
		++p[i];
	}
	qr.push_back(i);
}

int main() {
	int cas;
	scanf_s("%d", &cas);
	while (cas--) {
		int n;
		scanf_s("%d", &n);
		for (int i = 0; i < 5; ++i) {
			scanf_s("%d", &t[i]);
		}
		scanf_s("%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 temp = qr.front();
			qr.pop_front();
			run(temp);
		}
		if (cas) printf("\n");
	}
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值