POJ 3278 Catch That Cow
题目&题意
戳
给你\(n,m\)。
可以进行的操作有:
1.\(n + 1\)
2.\(n - 1\)
3.\(n * 2\)
问最少几步\(n==m\)。
有好几组数据(被坑了,\(qwq\))。
思路
\(bfs\)
\(Code\)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,step[100001];
queue<int> q;
bool pd[1000001];
inline int read(){
int x=0;bool f=0;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=!f;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
return f?-x:x;
}
bool bound(int x){
if(x<0||x>100000||pd[x]) return true;
return false;
}
void bfs(){
int t,temp;
q.push(n);
pd[n]=1;
while(!q.empty()){
t=q.front();
q.pop();
for(int i=1;i<=3;++i){
if(i==1) temp=t+1;
if(i==2) temp=t-1;
if(i==3) temp=t*2;
if(bound(temp)) continue;
step[temp]=step[t]+1;
if(temp==m) printf("%d\n",step[temp]);
q.push(temp);
pd[temp]=1;
}
}
}
int main(){
n=read(),m=read();
if(n>=m) printf("%d\n",n-m);//这个判断一定不要忘记
else bfs();
memset(pd,0,sizeof(pd));
return 0;
}