//算法: 裸搜 (BFS)
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int N, K;
const int MAXN = 100000 + 5;
int visited[2*(MAXN+10)];
struct Node{
int x;
int steps;
Node(int xx, int s) : x(xx), steps(s) {}
};
queue<Node> Q;
int main() {
cin >> N >> K;
memset(visited, 0, sizeof(visited));
Q.push(Node(N, 0));
visited[N] = 1;
while(!Q.empty()) {
Node temp = Q.front();
if(temp.x == K) {
//找到目标
cout << temp.steps << endl;
return 0;
}
else {
if(temp.x-1 >= 0 && !visited[temp.x-1]) {
visited[temp.x-1] = 1;
Q.push(Node(temp.x-1, temp.steps+1));
}
if(temp.x+1 <= MAXN && !visited[temp.x+1]) {
visited[temp.x+1] = 1;
Q.push(Node(temp.x+1, temp.steps+1));
}
if(temp.x*2 <= MAXN && !visited[temp.x*2]) {
visited[temp.x*2] = 1;
Q.push(Node(temp.x*2, temp.steps+1));
}
Q.pop();
}
}
return 0;
}
/*
//范围太大 搜索深度太深 (眼看都有100000左右了, 这还是没有考虑乘2的深度) 不宜使用dfs
//下面的代码严重超时!
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<map>
using namespace std;
int minTime = 1 << 30;
set<int> Q;
int N, K;
const int maxn = 100000 + 5;
int minT[maxn+5];
void dfs(int cur, int curTime) {
if(cur == K) {
minTime = min(minTime, curTime);
return ;
}
if(cur > 0 && cur < maxn) {
if(curTime > minT[cur] ) return ;
else
minT[cur] = curTime;
}
if(curTime > minTime ) return ;
if(cur < 0 || cur > 150000) return ;
if(!Q.count(cur+1)) {
Q.insert(cur+1);
dfs(cur+1, curTime+1);
}
Q.erase(cur+1);
if(!Q.count(cur-1)) {
Q.insert(cur-1);
dfs(cur-1, curTime+1);
}
Q.erase(cur-1);
if(!Q.count(cur*2)) {
Q.insert(cur*2);
dfs(cur*2, curTime+1);
}
Q.erase(cur*2);
return ;
}
int main() {
for(int i = 0; i < maxn; i++) {
minT[i] = (1 << 30);
}
Q.clear();
cin >> N >> K;
dfs(N, 0);
if(minTime < (1 << 30)) cout << minTime << endl;
return 0;
}
*/
POJ3278==抓住那头牛
最新推荐文章于 2023-10-28 10:54:52 发布