题干
C++实现
/**
输入样例:
12
1024 2048
8192 512
16384 1024
32768 8192
65536 8192
77824 1024
80896 3072
86016 1024
91136 5120
99328 512
104448 1024
112640 3072
1024 2560 10240 512 1024 6400 512 -1
输出样例:
104448 1024
112640 3072
1024 2048
8192 512
32768 1792
65536 8192
77824 1024
91136 5120*/
#include <stdio.h>
#include <list>
using namespace std;
struct Block {int startPos;int blockSize;
};
int main() {list<Block> freeList;int n;scanf("%d", &n);//输入for (int i = 0; i < n; ++i) {Block block;scanf("%d%d", &block.startPos, &block.blockSize);freeList.push_back(block);}int request;list<Block>::iterator it;while (1) {scanf("%d", &request);if (request == -1) {break;}list<Block>::iterator toAlloc = freeList.end();//表示要分配出去的盘块,开始初始化为无意义的freeList.end()int curLeast = 1e9+1;//记录最小的符合空闲块申请的大小for (it = freeList.begin(); it != freeList.end(); ++it) {if (it->blockSize == request) {toAlloc = it;break;}else if (it->blockSize > request && it->blockSize < curLeast) {toAlloc = it;curLeast = it->blockSize;}}if (toAlloc != freeList.end()) {//如果找到了可以分配的盘块while (toAlloc != freeList.begin()) {//要分配的盘块不是第一块Block front = freeList.front();freeList.pop_front();freeList.push_back(front);//把头块挂成尾块,方便出队}if (toAlloc->blockSize == request) {freeList.pop_front();}else {toAlloc->blockSize -= request;}}}//打印for (it = freeList.begin(); it != freeList.end(); ++it) {printf("%d %d\n", it->startPos, it->blockSize);}return 0;
}