# How to solve this ..?

problem:
(Problem - 520B - Codeforces)
can we solve this problem using bfs ??
is there any other approach ??

You can use dp to do it.

Yes, you can use BFS.

Code
``````#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define ld long double
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pb push_back
#define eb emplace_back
#define F first
#define S second
#define mp make_pair

template <typename Container>
void print(Container& container)
{
auto Start = container.begin(), End = container.end();
while (Start != End) cout << *(Start++) << "\n";
cout << '\n';
}

inline void solve()
{
int n, m;
cin >> n >> m;
queue <pair <int, int>> q;
vector <int> ans(1e6, -1);
q.emplace(n, 0);
while (!q.empty())
{
auto p = q.front();
ans[p.F] = p.S;
q.pop();
if (p.F == m)
{
cout << p.S << '\n';
return;
}
if (p.F <= 2 * m && ans[2 * p.F] == -1) q.emplace(2 * p.F, p.S + 1);
if (p.F - 1 >= 0 && ans[p.F - 1] == -1) q.emplace(p.F - 1, p.S + 1);
}
}

int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T = 1;
while (T--) solve();
}
``````

Just make sure that you donâ€™t visit unnecessary numbers.