没想到连水题都过不了了。。。
一开始用 IDA* 做,栈深度貌似太大
后来改用 BFS,继续挂,才发现自己连记忆化这种最简单的剪枝都没想到。。。
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
int n, m;
struct node
{
node(int s, int v):step(s), val(v){}
int step, val;
};
bool vis[20005];
queue<node> q;
int main()
{
while (cin>>n>>m) {
if (m <= n) {
printf("%d\n", n-m);
continue;
}
while(!q.empty()) q.pop();
q.push(node(0, n));
memset(vis, 0, sizeof(vis));
int ans = 0;
while (!q.empty()) {
node cur = q.front();
q.pop();
if(cur.val == m){
ans = cur.step;
break;
}
if(cur.val <= 0)
continue;
if (vis[cur.val]) {
continue;
}
if(cur.val > m)
{
q.push(node(cur.step+1, cur.val-1));
continue;
}
vis[cur.val] = true;
q.push(node(cur.step+1, cur.val*2));
q.push(node(cur.step+1, cur.val-1));
}
printf("%d\n", ans);
}
}