-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution_bf.cpp
More file actions
93 lines (77 loc) · 2.39 KB
/
solution_bf.cpp
File metadata and controls
93 lines (77 loc) · 2.39 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
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <limits>
using namespace std;
using ull = unsigned long long;
static ull getShownRoom(ull n, ull residue) {
// residue is assumed to be in [0, L-1] where L = 2*(n-1), n > 1.
if (n == 1) {
return 1;
}
ull nMinusOne = n - 1;
ull l = 2 * nMinusOne;
if (residue <= nMinusOne) {
return residue + 1;
}
return (l - residue) + 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
long long nIn, xIn, yIn, dIn;
cin >> nIn >> xIn >> yIn >> dIn;
ull n = static_cast<ull>(nIn);
ull x = static_cast<ull>(xIn);
ull y = static_cast<ull>(yIn);
ull d = static_cast<ull>(dIn);
// Special case: with one room, the shown room is always 1.
if (n == 1) {
cout << 0;
if (t > 0) cout << "\n";
continue;
}
ull nMinusOne = n - 1;
ull l = 2 * nMinusOne; // l >= 2 when n > 1
// Initial hidden coordinate z = x - 1, so residue is (x-1) mod l.
ull startRes = (x - 1) % l;
ull step = d % l;
/*
Brute-force baseline:
Enumerate the entire cycle generated by repeatedly adding 'step' modulo l.
This can be extremely slow for large n (l up to ~2e18), but is correct.
*/
// Compute cycle length (the number of additions needed to return to startRes).
ull cycleLen = 0;
{
ull res = startRes;
do {
res = (res + step) % l;
cycleLen++;
} while (res != startRes);
}
// Scan all residues in the cycle and track the minimum button presses.
const ull inf = numeric_limits<ull>::max();
ull best = inf;
ull res = startRes;
for (ull k = 0; k < cycleLen; k++) {
ull shown = getShownRoom(n, res);
if (shown == y) {
// k forward presses reaches this residue; cycleLen-k backward presses also reaches it.
ull presses = min(k, cycleLen - k);
best = min(best, presses);
}
res = (res + step) % l;
}
if (best == inf) {
cout << -1;
} else {
cout << best;
}
if (t > 0) cout << "\n";
}
return 0;
}