Memory Allocating Algorithm

Description:

#1198 : Memory Allocating Algorithm

分析:

思路:

代码来自hihoCoder #1198,好牛,可以想出用 deque 做,看来差距那么大啊。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <algorithm>
#include <deque>

using namespace std;

struct chunk {
int v, s, e;
};

int main() {
int n, m;
scanf("%d%d", &n, &m);
deque<chunk> que;
int c;
bool f = true;

for (int k = 1; k <= n; ++k) {
if (f) scanf("%d", &c);
if (que.empty()) {
que.push_back({ k, 0, c - 1 });
}
else {
bool flag = false;
int minK = n + 1;
int idx = -1;

for (int i = 0; i < que.size(); ++i) {
if (minK > que[i].v) {
minK = que[i].v;
idx = i;
}
if (i == 0) {
if (c - 1 < que[i].s) {
que.push_front({ k, 0, c - 1 });
flag = true;
break;
}
}
if (i == que.size() - 1) {
if (que[i].e + c < m) {
que.push_back({ k, que[i].e + 1, que[i].e + c });
flag = true;
break;
}
}
else {
if (que[i + 1].s - que[i].e - 1 >= c) {
que.insert(que.begin() + i + 1, { k, que[i].e + 1, que[i].e + c });
flag = true;
break;
}
}
}

if (!flag) {
que.erase(que.begin() + idx);
k--;
f = false;
}
else {
f = true;
}
}
}

sort(que.begin(), que.end(), [](const chunk &ch1, const chunk &ch2) {
return ch1.v < ch2.v;
});

for (int k = 0; k < que.size(); ++k) {
printf("%d %d\n", que[k].v, que[k].s);
}

return 0;
}