【问题描述】编程实现进程调度中的短作业优先调度算法。(括号内为相应的数字说明,不需要实现)
【输入形式】
【输出形式】
【样例输入】
3(表示进程个数)
process1 0 4(分别表示进程名称,到达时间和运行时间)
process2 2 7
process3 1 8
【样例输出】(按照调度顺序输出,下列各列分别表示进程名,到达时间,开始时间,运行时间,完成时间,周转时间,带权周转时间)
(每列之间用一个空格分割)
process1 0 0 4 4 4 1
process2 2 4 7 11 9 1.28571
process3 1 11 8 19 18 2.25
10.3333(表示平均周转时间)
1.5119(表示平均带权周转时间)
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class PCB{
public:
PCB(){
cin>>pname>>arrivetime>>runtime;
begintime=0;
endtime=0;
turntime=0;
weight_turn=0;
}
void display(){
cout<<pname<<" "<<arrivetime<<" "<<begintime<<" "<<runtime<<" "<<endtime<<" "<<turntime<<" "<<weight_turn<<endl;
}//分别表示进程名,到达时间,开始时间,运行时间,完成时间,周转时间,带权周转时间)
int get_arrivetime(){
return arrivetime;
}
int get_runtime(){
return runtime;
}
int get_begintime(){
return begintime;
}
int get_endtime(){
return endtime;
}
int get_turntime(){
return turntime;
}
float get_weight_turn(){
return weight_turn;
}
void setbegintime(int begintime){
this->begintime=begintime;
}
void setbendtime(int endtime){
this->endtime=endtime;
}
void setturntime(int turntime){
this->turntime=turntime;
}
void setweight(float weight_turn){
this->weight_turn=weight_turn;
}
private:
string pname;
int arrivetime;//到达时间
int begintime;//开始时间
int runtime;//运行时间
int endtime;//完成时间
int turntime;//周转时间
float weight_turn;//带权周转时间
};
bool compareByRun(PCB& p1,PCB& p2){
int t1=p1.get_runtime();
int t2=p2.get_runtime();
return t1<t2;
}
void SJF(vector<PCB>* p){
sort(p->begin()+1,p->end(),compareByRun);
vector<PCB>::iterator it=p->begin();
it->setbegintime(it->get_arrivetime());
it->setbendtime(it->get_begintime()+it->get_runtime());
it->setturntime(it->get_endtime()-it->get_arrivetime());
it->setweight(it->get_turntime()/it->get_runtime());
for(it++;it!=p->end();it++)
{
it->setbegintime((it-1)->get_endtime());
it->setbendtime(it->get_begintime()+it->get_runtime());
it->setturntime(it->get_endtime()-it->get_arrivetime());
it->setweight(float(it->get_turntime())/it->get_runtime());
}
}
void Avg_turn(vector<PCB>* p,float &avgturn,float &weighturn){
for(vector<PCB>::iterator it=p->begin();it!=p->end();it++)
{
avgturn+=it->get_turntime();
weighturn+=it->get_weight_turn();
}
avgturn/=p->size();
weighturn/=p->size();
}
int main()
{
vector<PCB>*p;
int n;
float avgturn=0.0,weighturn=0.0;
cin>>n;//输入进程数
p=new vector<PCB>[n];
for(int i=0;i<n;i++){
PCB temp;
p->push_back(temp);
}
sort(p->begin()+1,p->end(),compareByRun);//按照进入时间排序
SJF(p);
for(vector<PCB>::iterator it=p->begin();it!=p->end();it++)
(*it).display();
Avg_turn(p,avgturn,weighturn);
cout<<avgturn<<endl;//输出平均周转时间
cout<<weighturn<<endl;//输出平均带权周转时间
return 0;
}