10.7【全是紫题】 改错
T4 操作系统
题目大意
有若干个进程,每个进程都有编号,到达的时间,处理进程所需的时间,以及优先级。先到的进程则会一直占用cpu直到处理结束,如有优先级更高的进程到达,正在处理的优先级低的进程便会让位给更高优先级的进程,如有多个优先级相同的则选择到达时间最早的。让我们输出结束进程的编号与结束时间。
思路分析
这道题我们发现需要动态储存优先级更高的进程,便可以用优先队列来维护,因为我们要按照优先级来排序,所以我们需要在结构体写一个重载运算符。这样便可以达到以下两点操作
1: 新进程到达时直接插入队列:q.push(a[i])
2: 系统自动维护优先级顺序,最高优先级的进程总是在队首
思路实现
第一阶段:处理按时间到达的进程
for(int i=1;i<n;i++){
q.push(a[i]); // 新进程到达,加入就绪队列
now = a[i].st; // 更新当前时间到新进程到达时间
// 在当前进程间隔内执行就绪队列中的进程
while(!q.empty() && now < a[i+1].st && sum < n){
node x = q.top(); // 取优先级最高的进程
q.pop();
// 计算可执行时间:进程剩余时间与下个进程到达前的间隔取最小值
int time = mi(x.nt, a[i+1].st - now);
x.nt -= time; // 减少进程剩余时间
now += time; // 推进当前时间
if(x.nt == 0){ // 进程完成
cout << x.id << " " << now << endl;
sum++;
} else { // 进程未完成,重新加入队列
q.push(x);
}
}
}
第二阶段:处理剩余进程
while(!q.empty() && sum < n){
node x = q.top();
q.pop();
now += x.nt; // 直接执行完剩余时间
cout << x.id << " " << now << endl;
sum++;
}
完整代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e8+5;
struct node{
int id,st,nt,t;
friend bool operator<(const node &x,const node&y){
if(x.t!=y.t) return x.t<y.t;
else{
return x.st>y.st;
}
}
};
priority_queue<node> q;
node a[N];
inline int mi(int x,int y){
return x<y?x:y;
}
int main(){
ll n=1;
while(cin>>a[n].id>>a[n].st>>a[n].nt>>a[n].t) n++;
a[n+1].st=INT_MAX;
int now=0,sum=0;
for(int i=1;i<n;i++){
q.push(a[i]);
now=a[i].st;
while(!q.empty()&&now<a[i+1].st&&sum<n){
node x=q.top();
q.pop();
int time=mi(x.nt,a[i+1].st-now);
x.nt-=time;
now+=time;
if(x.nt==0){
cout<<x.id<<" "<<now<<endl;
sum++;
}else{
q.push(x);
}
}
}
while(!q.empty()&&sum<n){
node x=q.top();
q.pop();
now += x.nt;
cout<<x.id<<" "<<now<<endl;
sum++;
}
return 0;
}