-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChange_A_to_B.cpp
77 lines (65 loc) · 1.78 KB
/
Change_A_to_B.cpp
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
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
using namespace std;
#define ll long long int
// Function to find the minimum number of operations needed to go from A to B
ll minOperations(ll A, ll B, ll K)
{
if (A >= B)
return 0; // No operations needed if already at or beyond B
queue<pair<ll, ll>> q; // pair<current_value, current_operations_count>
unordered_set<ll> visited; // To keep track of visited states to avoid cycles
q.push(make_pair(A, 0));
visited.insert(A);
while (!q.empty())
{
ll current = q.front().first;
ll operations = q.front().second;
q.pop();
if (current == B)
{
return operations;
}
// Option 1: Increment current by 1
if (current + 1 == B)
{
return operations + 1;
}
if (current + 1 < B && visited.find(current + 1) == visited.end())
{
q.push(make_pair(current + 1, operations + 1));
visited.insert(current + 1);
}
// Option 2: Multiply current by K
if (current * K == B)
{
return operations + 1;
}
if (current * K < B && visited.find(current * K) == visited.end())
{
q.push(make_pair(current * K, operations + 1));
visited.insert(current * K);
}
}
// If we exit the loop, it means we could not find a path from A to B, which should not happen
return -1;
}
int main()
{
int T;
cin >> T;
vector<ll> results(T);
for (int i = 0; i < T; ++i)
{
ll A, B, K;
cin >> A >> B >> K;
results[i] = minOperations(A, B, K);
}
for (const auto &result : results)
{
cout << result << endl;
}
return 0;
}