cf 727A Transformation: from A to B(搜尋)
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
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
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.
OutputIf 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.
Examples input2 162output
YES 5 2 4 8 81 162input
4 42output
NOinput
100 40021output
YES
5
100 200 2001 4002 40021
這題的坑點只是太隱蔽了,n雖然給了10^9,讓你以為int內可以處理到,但是*10+1後就可能會爆int,一直以為是陣列開小的導致的M,結果是資料導致的。。
bfs
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; const int N = 100; struct node { long long num[N], x; int step;; }; int main() { long long a, b; while(scanf("%I64d %I64d", &a, &b)!=EOF) { queue<node>q; while(!q.empty()) { q.pop(); } node e; e.step=1, e.x=a, e.num[1]=a; q.push(e); int flag=0; while(!q.empty()) { node u; u = q.front(); q.pop(); if(u.x==b) { flag=1; printf("YES\n"); printf("%d\n",u.step); for(int i=1;i<=u.step;i++) { printf("%I64d%c",u.num[i],i==u.step?'\n':' '); } break; } if(u.x>b) continue; node u2 = u; u2.x = u.x*10+1; u2.step = u.step+1; u2.num[u2.step]=u2.x; q.push(u2); u.x = u.x*2; u.step = u.step+1; u.num[u.step]=u.x; q.push(u); } if(flag==0) printf("NO\n"); } return 0; }
dfs #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; const int N = 1000; long long num[N]; int k; int a, b, flag; int dfs( long long x) { if(flag==1) return 0; if(x==b) { flag=1; num[k++]=b; return 1; } if(x>b) return 0; if(dfs(x*10+1)) { num[k++]=x; return 1; } if(dfs(x*2)) { num[k++]=x; return 1; } return 0; } int main() { while(scanf("%d %d", &a, &b)!=EOF) { flag=0; k=0; dfs(a); if(flag==0) printf("NO\n"); else { printf("YES\n"); printf("%d\n",k); for(int i=k-1;i>=0;i--) { printf("%lld%c",num[i],i==0?'\n':' '); } } } return 0; }