思路
用結構體數組存儲pcb表,用優先隊列維護就緒的進程,優先隊列存儲pair<pcb的序號, 進程運行所需時間>,按照運行時間從小到大排序。然後運行即可。
例子
代碼
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
#define MP(a,b) make_pair(a, b)
typedef pair<int, int> P;///pcb中的序號 服務時間
const int maxn_program = 1e5 + 10;
const int maxn_name = 1e2 + 10;
int N; ///進程數目
int now_time; ///現在的時間
struct node{
char program_name[maxn_name]; ///進程名
int arrive_time; ///到達時間
int run_time; ///服務時間
int finished_time; ///完成時間
int wait_time; ///週轉時間
double with_value_wait_time; ///帶權週轉時間
char status = 'W'; ///進程狀態(W,R,F)
}program[maxn_program];
bool cmp(node a, node b){
if(a.arrive_time == b.arrive_time)
return a.run_time < b.run_time;
return a.arrive_time < b.arrive_time;
}
struct cmp2{
template<typename T, typename U>
bool operator()(T const& left, U const &right) {
if (left.second > right.second)
return true;
return false;
}
};
priority_queue <P, vector<P>, cmp2> que;
void out_put(){
printf("now_time:%d\n", now_time);
printf("%10s %10s %10s %10s %10s %10s %10s\n", "進程名", "到達時間", "服務時間", "完成時間", "週轉時間", "帶權週轉時間", "進程狀態");
for(int i = 1; i <= N; i++){
printf("%10s %10d %10d %10d %10d %10.2f %10c\n", program[i].program_name, program[i].arrive_time, program[i].run_time, program[i].finished_time, program[i].wait_time, program[i].with_value_wait_time, program[i].status);
}
}
void run_it(){
int pos = que.top().first;
now_time += que.top().second;
program[pos].finished_time = now_time;
program[pos].status = 'F';
program[pos].wait_time = now_time - program[pos].arrive_time;
program[pos].with_value_wait_time = (double)program[pos].wait_time / program[pos].run_time;
que.pop();
}
int main(){
printf("輸入進程數目:");
scanf("%d", &N);
printf("依次輸入各進程的進程名、到達時間、服務時間:");
for(int i = 1; i <= N; i++){
scanf("%s %d %d", &program[i].program_name, &program[i].arrive_time, &program[i].run_time);
}
///按到達時間排序,同時到達按照運行時間從短到長排序
sort(program + 1, program + 1 + N, cmp);
///out_put(); ///輸出pcb
for(int pos = 1; pos <= N;){
while(pos <= N && program[pos].arrive_time <= now_time){
que.push(MP(pos, program[pos].run_time));///壓入就緒隊列
pos++;
}
if(!que.empty())///如果que不爲空
run_it();///執行一個進程
out_put();
}
while(!que.empty()){
run_it();
out_put();///輸出pcb
}
return 0;
}
/*
5
A 0 4
B 1 3
C 2 5
D 3 2
E 4 4
*/