8
16
2015
0

[题解][HNOI2003]操作系统

关键字:堆,模拟。

Link&Limit


[洛谷2278]  [BZOJ1216]

时间限制:1000ms  空间限制:131072kb

Description


写一个程序来模拟操作系统的进程调度。假设该系统只有一个CPU,每一个进程的到达时间,执行时间和运行优先级都是已知的。其中运行优先级用自然数表示,数字越大,则优先级越高。

如果一个进程到达的时候CPU是空闲的,则它会一直占用CPU直到该进程结束。除非在这个过程中,有一个比它优先级高的进程要运行。在这种情况下,这个新的(优先级更高的)进程会占用CPU,而老的只有等待。

如果一个进程到达时,CPU正在处理一个比它优先级高或优先级相同的进程,则这个(新到达的)进程必须等待。

一旦CPU空闲,如果此时有进程在等待,则选择优先级最高的先运行。如果有多个优先级最高的进程,则选择到达时间最早的。

Input Format


输入包含若干行,每一行有四个自然数(均不超过10^8),分别是进程号,到达时间,执行时间和优先级。不同进程有不同的编号,不会有两个相同优先级的进 程同时到达。输入数据已经按到达时间从小到大排序。输入数据保证在任何时候,等待队列中的进程不超过15000个。

Output Format


按照进程结束的时间输出每个进程的进程号和结束时间。

Sample Input #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

Sample Output #1


1 6

3 19

5 30

6 32

8 34

4 35

7 40

2 42

模拟+堆的问题。在等待队列里的进程使用堆来维护就好,最麻烦的就是模拟进程的执行与调度过程。可以先将当前进程的剩余时间与新进程的到来时间对比,以决定新进程何时入堆。具体可见参考程序。

#include <stdio.h>
int st[500100],wt[500100];
long long rank[500100];
int heap[20010],tot = 0;
void add(int x)
{
    int i = ++tot,j = i>>1;
    heap[tot] = x;
    for(;i>1;i=j,j>>=1)
    {
        if(rank[x]>rank[heap[j]]) {heap[i] = heap[j]; heap[j] = x;}
        else break;
    }
}
void del()
{
    int i = 1,j = 2,x;
    x = heap[1] = heap[tot]; heap[tot--] = 0;
    for(;j<=tot;i=j,j=i<<1)
    {
        if(j<tot) if(rank[heap[j+1]]>rank[heap[j]]) j++;
        if(rank[x]<rank[heap[j]]) {heap[i] = heap[j]; heap[j] = x;}
        else break;
    }
}
int main()
{
    int i = 0,id,time = 0;
    while(scanf("%d",&id)>0)
    {
        scanf("%d%d%lld",&st[id],&wt[id],&rank[id]); i++;
        rank[id] = rank[id]*1000000000-i;
        while(tot)
        {
            if(time+wt[heap[1]]<=st[id])
            {
                printf("%d %d\n",heap[1],time+wt[heap[1]]);
                time += wt[heap[1]]; wt[heap[1]] = 0;
                del();
            }
            else
            {
                wt[heap[1]] -= st[id]-time;
                break;
            }
        }
        time = st[id];
        add(id);
    }
    while(tot)
    {
        printf("%d %d\n",heap[1],time+wt[heap[1]]); time += wt[heap[1]];
        wt[heap[1]] = 0;
        del();
    }
    return 0;
}
Category: 题解 | Tags: 模拟 bzoj 洛谷 | Read Count: 379

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

| Theme: Aeros 2.0 by TheBuckmaker.com