思路讲解
其实这道题目只需要一个关键结论,就是第 步只可能产生 或者 (当然这两个可能相等)。因此就猜一下就可以了。
当然,利用这个结论,也可以写一个记忆化 bfs,详细地来说,用一个 set 存一下,搜过的数字就不继续搜了。
while (!q.empty()) {
auto [x,step]=q.front();
q.pop();
if (x==K) {
cout<<step<<"\n";
return;
}
if (x<K) {
continue;
}
auto res=st.emplace(x/2,step+1);
bool con=!res.second;
if (!con) {
q.emplace(x/2,step+1);
}
res=st.emplace((x+1)/2,step+1);
con=!res.second;
if (!con){
q.emplace((x+1)/2,step+1);
}
}
cout<<-1<<"\n";AC代码
AC
https://codeforces.com/contest/2184/submission/357642090
代码
/**
* Problem: C. Huge Pile
* Contest: Codeforces Round 1072 (Div. 3)
* Judge: Codeforces
* URL: https://codeforces.com/contest/2184/problem/C
* Created: 2026-01-13 00:11:50
* Author: Gospel_rock
*/
#include <bits/stdc++.h>
#include <ranges>
#define all(vec) vec.begin(),vec.end()
#define lson(o) (o<<1)
#define rson(o) (o<<1|1)
#define SZ(a) ((long long) a.size())
#define debug(var) cerr << #var <<":"<<var<<"\n";
#define cend cerr<<"\n-----------\n"
#define fsp(x) fixed<<setprecision(x)
using namespace std;
using ll = long long;
using ull = unsigned long long;
using DB = double;
using LD = long double;
// using i128 = __int128;
using CD = complex<double>;
static constexpr ll MAXN = (ll)1e6+10, INF = (1ll<<61)-1;
static constexpr ll mod = 998244353; // (ll)1e9+7;
static constexpr double eps = 1e-8;
const double pi = acos(-1.0);
ll lT;
/*
*
*/
struct x_step {
ll x,step;
bool operator<(const x_step & o) const {
if (x!=o.x) return x<o.x;
return step<o.step;
}
x_step(ll x,ll step):x(x),step(step) {
}
};
void Solve() {
ll N,K;
cin >> N >> K;
queue<x_step> q;
q.push({N,0});
set<x_step> st;
while (!q.empty()) {
auto [x,step]=q.front();
q.pop();
if (x==K) {
cout<<step<<"\n";
return;
}
if (x<K) {
continue;
}
auto res=st.emplace(x/2,step+1);
bool con=!res.second;
if (!con) {
q.emplace(x/2,step+1);
}
res=st.emplace((x+1)/2,step+1);
con=!res.second;
if (!con){
q.emplace((x+1)/2,step+1);
}
}
cout<<-1<<"\n";
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> lT;
while(lT--)
Solve();
return 0;
}
/*
AC
https://codeforces.com/contest/2184/submission/357642090
*/