Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:
multiply the current number by 2 (that is, replace the number x by 2·x);append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasily to transform the number a into the number b using only the operations described above, or find that it is impossible.Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform a into b.
Input
The first line contains two positive integers a and b (1 ≤ a < b ≤ 109) — the number which Vasily has and the number he wants to have.
Output
If there is no way to get b from a, print “NO” (without quotes).
Otherwise print three lines. On the first line print “YES” (without quotes). The second line should contain single integer k — the length of the transformation sequence. On the third line print the sequence of transformations x1, x2, …, xk, where:
x1 should be equal to a,xk should be equal to b,xi should be obtained from xi - 1 using any of two described operations (1 < i ≤ k).If there are multiple answers, print any of them.
Sample Input
2 162
Sample Output
YES 5 2 4 8 81 162
解题思路
DFS 通过DFS遍历每种情况,记录选择路径,直到n>=m结束,n==m代表有答案,输出即可。若n>m,返回上一层DFS继续遍历。
规律: 偶数 则可以推出是由操作1得来 将b/2继续迭代 奇数 则由操作2的来 将b=(b-1)/10后继续迭代 ,可以发现如果 (b-1)%10!=0 则没有x*10+1=b 退出即可
AC代码1(DFS):
#include <iostream> #include <vector> using namespace std; #define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0) typedef long long ll; ll n,m,cnt=0; bool flag=false; ll ans[35]; void dfs(ll x,int pos) { ans[pos]=x; if(x>=m) { if(x==m) { flag=true; cnt=pos; } return; } dfs(x*2,pos+1); if(flag) return; dfs(x*10+1,pos+1); } int main() { SIS; cin >> n >> m; dfs(n,0); if(flag) { cout << "YES" << endl << cnt+1 << endl; for(int i=0;i<=cnt;i++) cout << ans[i] << (i==cnt?'\n':' '); } else cout << "NO" << endl; return 0; }AC代码2(规律):
#include <iostream> #include <algorithm> #include <vector> using namespace std; #define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0) int main() { SIS; int n,m; vector<int> v; cin >> n >> m; v.push_back(m); while(m>n) { if((m-1)%10==0) m/=10,v.push_back(m); else if(!(m&1)) m/=2,v.push_back(m); else break; } if(m==n) { int len = v.size(); cout << "YES" << endl << len << endl; for(int i=len-1;i>=0;i--) cout << v[i] << (i==0?'\n':' '); } else cout << "NO" << endl; return 0; }