题目链接
代码
无脑BFS,1700ms
#include<bits/stdc++.h>
using namespace std;
const int MOD = 32768;
int x;
int main() {
int n;
cin >> n;
while (n--) {
cin >> x;
int ans = INT_MAX;
queue<pair<int, int>> q;
vector<int> visited(MOD);
visited[x] = 1;
q.push({x, 0});
while (!q.empty()) {
auto node = q.front();
q.pop();
if (node.second >= ans)
break;
ans = min(ans, MOD - node.first + node.second);
if (node.first == 0) {
ans = node.second;
break;
}
if (!visited[(node.first << 1) % MOD]) {
visited[(node.first << 1) % MOD] = 1;
q.push({(node.first << 1) % MOD, node.second + 1});
}
if (!visited[(node.first + 1) % MOD]) {
visited[(node.first + 1) % MOD] = 1;
q.push({(node.first + 1) % MOD, node.second + 1});
}
}
printf("%d", ans);
if (n != 0)
printf(" ");
}
}