[HNOI2003]操作系统

嘟嘟嘟

这道题就是一个模拟。

首先我们建一个优先队列,存所有等待的进程,当然第一关键字是优先级从大到小,第二关键字是到达时间从小到大。然后再建一个指针Tim,代表cpu运行的绝对时间。

然后分一下几种情况:

1.如果等待队列为空,那直接调到当前该执行的进程的到达时间,并把它放进等待队列(可以这么理解,每一个进程运行完之前都要进入等待队列)。

2.如果非空,还要分两种情况:

  (1).当前队首的进程 j 能在当前该执行的进程 i 到达前运行完,那么就把 j 踢出队列,并输出,Tim 加上 j 的运行时间。

  (2).j 在 i 之前运行不完,那么 j 在 i 到达之前能运行多少,就把他的运行时间减去多少,然后把 i 和 j 都放进队列里。

总的来说,Tim 指针每一次总是跳到最近的时间点,然后执行当前优先级最高的进程。这样有的进程就可能不是一次执行完,不过这并不影响,因为如果他的优先级高的话,一定会在下一个循环中继续执行。

这个循环的终止条件是将所有的进程都放进了等待队列里,所以只用在循环外面每一次输出队首的进程就行了。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<cstdlib>
 7 #include<vector>
 8 #include<queue>
 9 #include<stack>
10 #include<cctype>
11 using namespace std;
12 #define enter puts("")
13 #define space putchar(' ')
14 #define Mem(a) memset(a, 0, sizeof(a))
15 typedef long long ll;
16 typedef double db;
17 const int INF = 0x3f3f3f3f;
18 const db eps = 1e-8;
19 const int maxn = 1e7 + 5;
20 inline ll read()
21 {
22     ll ans = 0;
23     char ch = getchar(), last = ' ';
24     while(!isdigit(ch)) last = ch, ch = getchar();
25     while(isdigit(ch)) ans = (ans << 3) + (ans << 1) + ch - '0', ch = getchar();
26     if(last == '-') ans = -ans;
27     return ans;
28 }
29 inline void write(ll x)
30 { 
31     if(x < 0) putchar('-'), x = -x;
32     if(x >= 10) write(x / 10);
33     putchar(x % 10 + '0');
34 }
35 
36 struct Node
37 {
38     int id, com, tim, lev;
39     bool operator < (const Node& other)const
40     {
41         return lev < other.lev || (lev == other.lev && com > other.com);
42     }
43 }a[maxn];
44 priority_queue<Node> q;
45 int n = 0;
46 
47 int main()
48 {
49 //    freopen("ha.in", "r", stdin);
50     while(scanf("%d%d%d%d", &a[n + 1].id, &a[n + 1].com, &a[n + 1].tim, &a[n + 1].lev) != EOF) n++;
51     int Tim = 0;
52     int i = 1;
53     while(i <= n)
54     {
55         if(q.empty()) Tim = a[i].com, q.push(a[i]), i++;    //case 1 
56         else
57         {
58             Node now = q.top(); q.pop();
59             if(Tim + now.tim <= a[i].com)                    //case 2.1 
60             {
61                 Tim += now.tim;
62                 write(now.id); space; write(Tim); enter;
63             }
64             else                                            //case 2.2
65             {
66                 now.tim -= a[i].com - Tim;
67                 Tim = a[i].com;
68                 q.push(now); q.push(a[i]); i++;
69             }
70         }
71     }
72     while(!q.empty())
73     {
74         Node now = q.top(); q.pop();
75         Tim += now.tim;
76         write(now.id); space; write(Tim); enter;
77     }
78     return 0;
79 }
View Code
原文地址:https://www.cnblogs.com/mrclr/p/9533727.html