Problem
Jesse is building his own operating system and now faces the task of building the process scheduling and the memory management feature. He has laid down the rules of how he is going to do it. It’s as follows:
- If a process needs to be executed and memory is available, the process is given the required amount of memory.
- If a process needs to be executed and memory is not available, Jesse will wait until a few processes are completed which will free up enough memory and then he will assign it to the process.
- Once a process is assigned some memory, it can’t be removed from the memory until it’s completed.
- The processes should be executed in the given order. A process j can’t be allocated memory before process
i , if i<j .
Jesse is busy with other stuff and needs your help in implementing this. Can you help him do this?
Assume that the time taken to allocate memory to a process is 0 .
Input Format
The first line contains two integers
Constraints
- 1≤n≤105
- 1≤m≤109
- 1≤duri≤106
- 1≤memi≤n
Output Format
Print in a single line, the total time taken to execute all the given processes.
Sample Input
5 20
5 10
6 11
4 8
2 9
3 10
Sample Output
14
Solution
Tip
- 优先队列
- 重定义操作符
- 数据类型 long long
Code
#include <cmath>
#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
struct comp{
bool operator()(vector<long long> x, vector<long long> y){
return x[0] > y[0];
}
};
int os(){
int n, m;
cin >> n >> m;
queue<vector<int>> rec;
for(int i = 0; i < n; i++){
int dur, mem;
cin >> dur >> mem;
vector<int> temp;
temp.push_back(dur);
temp.push_back(mem);
rec.push(temp);
}
priority_queue<vector<long long>, vector<vector<long long>>, comp> q;
int mem_left = m;
long long time = 0;
while(!rec.empty()){
while(!rec.empty() && rec.front()[1] <= mem_left){
vector<long long> temp = rec.front();
rec.pop();
temp[0] += time;
mem_left -= temp[1];
q.push(temp);
}
while(!q.empty()){
if(!rec.empty() && rec.front()[1] <= mem_left){
break;
}
vector<long long> temp = q.top();
q.pop();
time = temp[0];
mem_left += temp[1];
}
}
while(!q.empty()){
time = q.top()[0];
q.pop();
}
return time;
}