鏈接:https://ac.nowcoder.com/acm/problem/20030
來源:牛客網
題目描述
寫一個程序來模擬操作系統的進程調度。假設該系統只有一個CPU,每一個進程的到達時間,執行時間和運行優先級都是已知的。其中運行優先級用自然數表示,數字越大,則優先級越高。
如果一個進程到達的時候CPU是空閒的,則它會一直佔用CPU直到該進程結束。除非在這個過程中,有一個比它優先級高的進程要運行。在這種情況下,這個新的(優先級更高的)進程會佔用CPU,而老的只有等待。
如果一個進程到達時,CPU正在處理一個比它優先級高或優先級相同的進程,則這個(新到達的)進程必須等待。一旦CPU空閒,如果此時有進程在等待,則選擇優先級最高的先運行。如果有多個優先級最高的進程,則選擇到達時間最早的。
輸入描述:
輸入文件包含若干行,每一行有四個自然數(均不超過108),分別是進程號,到達時間,執行時間和優先級。不同進程有不同的編號,不會有兩個相同優先級的進程同時到達。 輸入數據已經按到達時間從小到大排序。輸入數據保證在任何時候,等待隊列中的進程不超過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 6 3 19 5 30 6 32 8 34 4 35 7 40 2 42
思路:
使用優先隊列,對於剛輸入的每個進程,先運行完所有完成時間在它之前的進程,然後push進隊。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf = 0x3f3f3f3f;
const double eps = 1e-12;
const double PI = acos(-1.0);
const int N = 25;
struct node
{
int num, len, pri;
bool operator < (const node &a)const
{
if(a.pri != pri)
return pri < a.pri;
else
return num >= a.num;
}
};
int main()
{
priority_queue<node>q;
int timm = 0;
int a, b, c, d;
while(~scanf("%d%d%d%d", &a, &b, &c, &d))
{
while(q.size())
{
node tmp = q.top();
q.pop();
if(tmp.len + timm <= b)
{
timm += tmp.len;
cout<<tmp.num<<' '<<timm<<'\n';
}
else
{
tmp.len -= b - timm;
q.push(tmp);
break;
}
}
node now;
now.num = a;
now.pri = d;
now.len = c;
timm = b;
q.push(now);
}
while(q.size())
{
node tmp = q.top();
q.pop();
timm += tmp.len;
cout<<tmp.num<<' '<<timm<<'\n';
}
return 0;
}