-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1037. Memory Management.java
More file actions
118 lines (96 loc) · 3.47 KB
/
1037. Memory Management.java
File metadata and controls
118 lines (96 loc) · 3.47 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.io.FileInputStream;
import java.io.IOException;import java.io.InputStream;
import java.util.Scanner;
import java.util.TreeMap;
import javax.xml.stream.events.NotationDeclaration;
public class MemoryManagement {
public static class TreeNode implements Comparable<TreeNode> {
public long timestamp;
public int id;
public TreeNode(int id, long timestamp){
this.timestamp = timestamp;
this.id = id;
}
@Override
public int compareTo(TreeNode obj) {
if (this.timestamp < obj.timestamp) {
return -1;
} else if (this.timestamp == obj.timestamp) {
if (this.id < obj.id) {
return -1;
} else if (this.id == obj.id) {
return 0;
} else {
return 1;
}
} else {
}
return 1;
}
}
public static void main(String[] args) throws IOException {
TreeMap<TreeNode, Integer> blocks = new TreeMap<TreeNode, Integer>();
/* references to the blocks nodes in the tree */
TreeNode nodes[] = new TreeNode[30001];
Scanner sc = new Scanner(System.in);
int N = 30000;
int T = 10*60; /* 10 min */
int minFreeBlock = 1;
int oldtime = 0;
while (sc.hasNext()) {
int time = 0;
char c = 0;
try {
time = sc.nextInt();
c = (char) sc.next().charAt(0);
} catch (Exception e) {
System.exit(0);
}
/* Remove expired blocks */
if (time != oldtime) {
TreeNode n = null;
while (!blocks.isEmpty()) {
n = blocks.firstKey();
/* expired */
if (time - n.timestamp >= T ) {
blocks.remove(n);
nodes[n.id] = null;
if (n.id < minFreeBlock) {
minFreeBlock = n.id;
}
} else {
break;
}
}
oldtime = time;
}
if (c == '+') {
System.out.println(minFreeBlock);
TreeNode n = new TreeNode(minFreeBlock, time);
blocks.put(n, minFreeBlock);
nodes[n.id] = n;
for (int i = minFreeBlock + 1; i <= 30000; i++) {
if (nodes[i] == null) {
minFreeBlock = i;
break;
}
}
} else {
/* request for block access */
int blockNo = sc.nextInt();
//System.out.println(blockNo);
if (blockNo > N || nodes[blockNo] == null) {
System.out.println("-");
}
else {
/* update block time */
blocks.remove(nodes[blockNo]);
nodes[blockNo].timestamp = time;
blocks.put(nodes[blockNo], blockNo);
System.out.println("+");
}
}
}
sc.close();
}
}