-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution_bf.cpp
More file actions
69 lines (55 loc) · 1.67 KB
/
solution_bf.cpp
File metadata and controls
69 lines (55 loc) · 1.67 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
#include <algorithm>
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
/*
Brute-force baseline (intentionally non-optimal):
Consider each gate position as a node in an unweighted graph.
From position p, we can go to p + a for every integer a such that:
- 1 <= a <= m
- a % k != 0
- p + a <= x (must not overshoot, since we need to land exactly on x)
The minimum number of moves equals the shortest path length from 0 to x,
which is found via a plain BFS over positions.
This is correct but can be extremely slow / memory-heavy for large x.
*/
static long long solveOneCase(long long x, long long k, long long m) {
queue<long long> bfsQueue;
unordered_map<long long, long long> dist;
dist[0] = 0;
bfsQueue.push(0);
while (!bfsQueue.empty()) {
long long p = bfsQueue.front();
bfsQueue.pop();
long long curDist = dist[p];
if (p == x) {
return curDist;
}
long long maxJump = min(m, x - p);
for (long long a = 1; a <= maxJump; a++) {
if (a % k == 0) {
continue;
}
long long nextPos = p + a;
if (dist.find(nextPos) == dist.end()) {
dist[nextPos] = curDist + 1;
bfsQueue.push(nextPos);
}
}
}
// With k >= 2, jump length 1 is always allowed, so x is always reachable.
return -1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
long long x, k, m;
cin >> x >> k >> m;
cout << solveOneCase(x, k, m) << "\n";
}
return 0;
}