题解 P2278 【[HNOI2003]操作系统】

· · 题解

用优先队列q来模拟我们的cpu,最开始时,cpu中没有进程,因此,我们把第一个进程放进去,第二个进程进来时会有选择,有几种可能,要进入的进程的开始时间在前面那个进程结束时间之后,我们相当于可以直接完场此时cpu中的进程,将时间节点更新当前结束时间,第二种情况,当前cpu中进程的结束时间在要进来的这个进程开始时间之后,这是我们选择比较优先级,如果cpu中进程的优先级小,那么当前进程只会执行一半,我们算出他能够执行的时间,更新这个进程并且重新放回cpu中,并将即将进入的进程放进去,,继续等待下一步处理,当前在q中的所有进程,都已经不用管开始时间了,因为如果在q中,就表明要么已经执行过,所以在门口等待执行,要么是即将执行,他们的st都已经不存在什么意义,都已经是迫不及待等待了,所以q中的东西只用管优先级。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct node{
    int id,st,re,pr;
    bool operator < (const node &a)const{
        if(pr==a.pr)  return st>a.st;
        else return pr<a.pr;
    }
};
node c;
long long ti;
priority_queue<node>q;
int main(){
    while(scanf("%d%d%d%d",&c.id,&c.st,&c.re,&c.pr)!=EOF){
        while(!q.empty()&&ti+q.top().re<=c.st){
            node b=q.top();
            q.pop();
            printf("%d %lld\n",b.id,ti+b.re);
            ti+=b.re;
        }
        if(!q.empty()){
            node d=q.top();
            q.pop();
            d.re=d.re-c.st+ti;
            q.push(d);
        }
        q.push(c);
        ti=c.st;
    }
    while(!q.empty()){
        node f=q.top();
        q.pop();
        ti+=f.re;
        printf("%d %lld\n",f.id,ti);
    }
    return 0;
}