LRJ-Example-06-01-Uva210
1 #define _CRT_SECURE_NO_WARNINGS 2 3 #include <cstdio> 4 #include <cstdlib> 5 #include <cstring> 6 #include <algorithm> 7 #include <vector> 8 #include <istream> 9 #include <iostream> 10 #include <deque> 11 #include <queue> 12 13 using namespace std; 14 15 int t[5]; // unit execution times, assignment, print, lock, unlock, end 16 int quantum; 17 18 const int N = 15; // up to 10 programs 19 vector<string> prog[N]; // programs 20 int pc[N]; // program counter for each program 21 22 bool lock; 23 deque<int> qr;//ready queue of program ID 24 queue<int> qb;//blocked queue of program ID 25 26 int var[26]; // values of 26 shared variables 27 28 void run(int i) // i -- program ID 29 { 30 int rt = quantum; 31 string stmt; 32 while (rt > 0) 33 { 34 stmt = prog[i][pc[i]]; 35 if (stmt[2] == '=') // assignment 36 { 37 rt -= t[0]; 38 // decimal number less than 100 39 int v = stmt[4] - '0'; 40 if (stmt.size() == 6) v = v * 10 + stmt[5] - '0'; 41 var[stmt[0] - 'a'] = v; 42 } 43 else if (stmt[2] == 'i') //print 44 { 45 rt -= t[1]; 46 printf("%d: %d\n", i, var[stmt[6] - 'a']); 47 } 48 else if (stmt[2] == 'c') //lock 49 { 50 51 if (lock) 52 { 53 // program counter is not incremented 54 // the first statement this program will execute when it runs will be the lock statement failed 55 qb.push(i); 56 return; // lose any of its quantum remaining 57 } 58 else 59 { 60 rt -= t[2]; 61 lock = true; 62 } 63 64 } 65 else if (stmt[2] == 'l') //unlock 66 { 67 rt -= t[3]; 68 lock = false; 69 if (!qb.empty()) 70 { 71 qr.push_front(qb.front()); 72 qb.pop(); 73 } 74 } 75 else 76 return; //end 77 78 ++pc[i]; // increment the program counter 79 } 80 qr.push_back(i); 81 } 82 83 int main() 84 { 85 int T, n; 86 scanf("%d", &T); 87 while (T--) 88 { 89 scanf("%d", &n); // number of programs 90 91 for (int i = 0; i < 5; i++) 92 scanf("%d", &t[i]); 93 94 scanf("%d", &quantum); 95 96 for (int i = 1; i <= n; i++) 97 { 98 prog[i].clear(); 99 string s; 100 while (getline(cin, s)) 101 { 102 if (s == "") continue; // empty line 103 prog[i].push_back(s); 104 if (s == "end") break; 105 } 106 qr.push_back(i); 107 } 108 109 memset(pc, 0, sizeof(pc)); 110 memset(var, 0, sizeof(var)); // all variables are initially set to zero 111 112 while (!qr.empty()) 113 { 114 int id = qr.front(); 115 qr.pop_front(); 116 run(id); 117 } 118 119 if (T) 120 printf("\n"); 121 } 122 return 0; 123 }