POJ - 1193 内存分配

POJ - 1193 内存分配

数据结构:

  1. 等待队列:(内存长度, 占用时间):queue
  2. 内存使用情况:(起始下标,长度),线性扫描、删除、插入:set
  3. 小根堆:(释放时间key,起始下标),priority_queue

算法流程:
新来一个请求:(T,M,P)

  1. 释放掉所有 释放时间 <= T 的内存,每次释放之后,都要判断等待队列的队头是否可以满足
  2. 判断(T,M,P)是否可以满足,如果不可以,则插入等待队列
#include<iostream>
#include<queue>
#include<set>
#include<vector>
using namespace std;

typedef pair<int, int> PII;
queue<PII> waits;       // (first: 内存长度,second: 占用时间)
set<PII> runs;        // (first: 起始下标,sercond:长度)
priority_queue<PII,vector<PII>, greater<PII> > endts;       // (first: 释放时间,second: 起始下标)
int tm, cnt;

bool give(int t, int m, int p)
{
    for (set<PII>::iterator it = runs.begin(); it != runs.end(); it ++ )
    {
        set<PII>::iterator jt = it;
        jt ++ ;
        if (jt != runs.end())
        {
            if (m <= jt->first - (it->first + it->second - 1) - 1)
            {
                int start = it->first + it->second;
                runs.insert((PII){start, m});
                endts.push((PII){t + p, start});
                return true;
            }
        }
    }
    return false;
}

void finish(int t)
{
    while (endts.size() && endts.top().first <= t)
    {
        int f = endts.top().first;
        while (endts.size() && endts.top().first == f)
        {
            PII top = endts.top();
            endts.pop();
            set<PII>::iterator it = runs.lower_bound((PII){top.second, 0});
            runs.erase(it);
        }

        tm = f;
        while (waits.size())
        {
            PII front = waits.front();
            if (give(f, front.first, front.second))
            {
                waits.pop();
            }
            else break;
        }
    }
}

int main()
{
    int n;cin >> n;
    runs.insert((PII){-1, 1}), runs.insert((PII){n, 1});
    int t, m, p;
    while (cin >> t >> m >> p, t || m || p)
    {
        finish(t);
        if (!give(t, m, p))
        {
            waits.push((PII){m, p});
            cnt ++ ;
        }
    }
    finish(2e9);

    cout << tm << endl << cnt << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wa_Automata

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值