题目描述
写一个程序来模拟操作系统的进程调度。假设该系统只有一个CPU,每一个进程的到达时间,执行时间和运行优先级都是已知的。其中运行优先级用自然数表示,数字越大,则优先级越高。
如果一个进程到达的时候CPU是空闲的,则它会一直占用CPU直到该进程结束。除非在这个过程中,有一个比它优先级高的进程要运行。在这种情况下,这个新的(优先级更高的)进程会占用CPU,而老的只有等待。
如果一个进程到达时,CPU正在处理一个比它优先级高或优先级相同的进程,则这个(新到达的)进程必须等待。
一旦CPU空闲,如果此时有进程在等待,则选择优先级最高的先运行。如果有多个优先级最高的进程,则选择到达时间最早的。
输入输出格式
输入格式:
输入包含若干行,每一行有四个自然数(均不超过10^8),分别是进程号,到达时间,执行时间和优先级。不同进程有不同的编号,不会有两个相同优先级的进程同时到达。输入数据已经按到达时间从小到大排序。输入数据保证在任何时候,等待队列中的进程不超过15000个。
输出格式:
按照进程结束的时间输出每个进程的进程号和结束时间。
输入输出样例
输入样例#1: 复制
1 1 5 3 2 10 5 1 3 12 7 2 4 20 2 3 5 21 9 4 6 22 2 4 7 23 5 2 8 24 2 4
输出样例#1: 复制
1 6 3 19 5 30 6 32 8 34 4 35 7 40 2 42
思路:注意输入的数组开大(因为没给数据范围啊) 还有注意当前队列里存不存在
#include<bits/stdc++.h>
#pragma GCC optimize(3)
using namespace std;
#define maxn 1500005
#define mod 1e9+7
#define inf 1e18
typedef long long ll;
struct Why
{
ll num,gettime,time,val;
}arr[maxn];
ll n;
struct Whhy
{
ll num,t,val,gettime;
Whhy(ll a,ll b,ll c,ll d)
{
num = a;
t = b;
val = c;
gettime = d;
}
bool operator < (const Whhy temp) const
{
if(val != temp.val)
return val < temp.val;
else
return gettime > temp.gettime;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
while(cin >> arr[n].num >> arr[n].gettime >> arr[n].time >> arr[n].val)
n++;
priority_queue<Whhy>A;
ll i = 0;
A.push(Whhy(arr[i].num,arr[i].time,arr[i].val,arr[i].gettime));
ll now = arr[0].gettime;
while(!A.empty())
{
Whhy temp = A.top();
A.pop();
//cout << "这次 " << temp.num << " " << temp.t << " " << now << endl;
if(i < n-1)
{
if(temp.t + now <= arr[i+1].gettime && A.size() == 0)
{
cout << temp.num << " " << temp.t+now << endl;
A.push( Whhy( arr[i+1].num, arr[i+1].time, arr[i+1].val, arr[i+1].gettime ) );
now = arr[i+1].gettime;
i++;
}
else if(temp.t + now <= arr[i+1].gettime && A.size() != 0)
{
cout << temp.num << " " << temp.t+now << endl;
now = now + temp.t;
}
else
{
//cout << "这次 " << temp.num << " " << temp.t << " " << now << endl;
A.push( Whhy(temp.num, temp.t+now-arr[i+1].gettime, temp.val, temp.gettime) );
A.push( Whhy(arr[i+1].num, arr[i+1].time, arr[i+1].val, arr[i+1].gettime) );
now = arr[i+1].gettime;
i++;
}
}
else
{
cout << temp.num << " " << temp.t+now << endl;
now = now + temp.t;
}
}
return 0;
}