Skip to content

Commit 7cd52d0

Browse files
committed
top 1034
1 parent cc56902 commit 7cd52d0

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
#include <queue>
3+
#include <cstring>
4+
using namespace std;
5+
const int LIMIT = 120000;
6+
const int OFFSET = 120000;
7+
8+
// BFS to find the minimum steps to reach from A to B using operations +1, -1, and *N
9+
int minSteps(int A, int B, int N) {
10+
bool visited[LIMIT + OFFSET + 1] = {false};
11+
if (A == B) return 0;
12+
13+
queue<pair<int, int>> q; // (value, steps)
14+
q.push({A, 0});
15+
visited[A + OFFSET] = true;
16+
17+
while (!q.empty()) {
18+
auto [curr, steps] = q.front();
19+
q.pop();
20+
21+
if (curr == B) return steps;
22+
23+
if (curr < LIMIT && !visited[curr + 1 + OFFSET]) {
24+
visited[curr + OFFSET] = true;
25+
q.push({curr + 1, steps + 1});
26+
}
27+
28+
if (curr > -LIMIT && !visited[curr - 1 + OFFSET]) {
29+
visited[curr - 1 + OFFSET] = true;
30+
q.push({curr - 1, steps + 1});
31+
}
32+
33+
int mult = curr * N;
34+
if (mult >= -LIMIT && mult <= LIMIT && !visited[mult + OFFSET]) {
35+
visited[mult + OFFSET] = true;
36+
q.push({mult, steps + 1});
37+
}
38+
}
39+
40+
return -1;
41+
}
42+
43+
int main() {
44+
ios::sync_with_stdio(false);
45+
int K;
46+
cin >> K;
47+
48+
int A, B, N;
49+
for (int i = 0; i < K; i++) {
50+
cin >> A >> B >> N;
51+
cout << minSteps(A, B, N) << endl;
52+
}
53+
54+
return 0;
55+
}

0 commit comments

Comments
 (0)