-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.pas
101 lines (87 loc) · 2.09 KB
/
main.pas
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
program Aoc2020Day15;
uses SysUtils;
const
Capacity = 30 * 1000 * 1000 + 10;
var
input : array[0..0] of String = (
{'0,3,6',
'1,3,2',
'2,1,3',
'1,2,3',
'2,3,1',
'3,2,1',
'3,1,2',
}
'6,3,15,13,1,0'
);
sample : array of Int64;
hashtable : array of Int64;
i, j, sampleSize : Int64;
procedure SavePrevPos(value: Int64; pos: Int64);
begin
Assert(Value < Capacity);
hashtable[value] := pos;
end;
function GetPrevPos(value: Int64): Int64;
begin
Assert(Value < Capacity);
GetPrevPos := hashtable[Value];
end;
{
function FindPrev(size, prev: Int64): Int64;
begin
for i := size - 1 downto 0 do
if sample[i] = prev then
Exit(i);
Exit(-1);
end;
}
procedure SolveSample(n: Int64);
var
prevIndex : Int64;
begin
while sampleSize < n do
begin
prevIndex := GetPrevPos(sample[sampleSize - 1]);
SavePrevPos(sample[sampleSize - 1], sampleSize - 1);
if prevIndex < 0 then
sample[sampleSize] := 0
else
sample[sampleSize] := sampleSize - (prevIndex + 1);
inc(sampleSize);
end;
WriteLn(n, 'th: ', sample[sampleSize - 1]);
end;
procedure InitSample(input : String);
var
start, finish : Int64;
begin
start := 1;
finish := 1;
sampleSize := 0;
while start <= Length(input) do
begin
while (finish <= Length(input)) and (input[finish] <> ',') do
begin
inc(finish);
end;
if sampleSize > 0 then
SavePrevPos(sample[sampleSize - 1], sampleSize - 1);
sample[sampleSize] := StrToInt64(copy(input, start, finish - start));
inc(sampleSize);
start := finish + 1;
finish := start;
end;
end;
begin
setLength(sample, Capacity);
setLength(hashtable, Capacity);
for i := 0 to Length(input) - 1 do
begin
WriteLn('Sample: ', input[i]);
for j := 0 to Capacity - 1 do hashtable[j] := -1;
InitSample(input[i]);
{SolveSample(2020);}
SolveSample(30 * 1000 * 1000);
end;
end.