USACO 2022 January Contest Silver Division - Searching for Soulmates#
Problem link: here
Solution Author: Stefan Dascalescu
Problem Solution#
We notice that it takes no more than \(\log x\) operations to bring \(x\) to \(1\). We create two vectors (one for A and one for B) that count how many operations it takes to bring \(x\) to state \(x'\) and take all the combinations \((B'-A'+i+j)\), and the minimum of these is the answer.
Source code#
The source code in C++ can be seen below.
#include <climits>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int t;
void solve() {
long long a, b;
cin >> a >> b;
vector<long long> div1 = {a}, div2 = {b};
while (a > 1) {
if (a % 2) {
a++;
} else
a /= 2;
div1.push_back(a);
}
while (b > 1) {
if (b % 2) {
b--;
}
else
b /= 2;
div2.push_back(b);
}
long long ret = LLONG_MAX;
for (int i = 0; i < div1.size(); i++) {
for (int j = 0; j < div2.size(); j++) {
if (div1[i] <= div2[j]) {
ret = min(ret, div2[j] - div1[i] + i + j);
}
}
}
cout << ret << "\n";
return;
}
int main() {
cin >> t;
while (t--) {
solve();
}
return 0;
}