NOI:2971 抓住那头牛
程序员文章站
2022-06-12 09:19:59
...
题目链接:http://noi.openjudge.cn/ch0205/2971/
题解:这道题可以使用典型的BFS求解,一提到求最短路问题,就会想到BFS(需要有这个意识)
#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;
int size;
int n,k;
struct point {
int x,tmp;
point(int x1,int tmp1){
x=x1;
tmp=tmp1;
}
point(){
x=0;
tmp=0;
}
};
queue<point> a;
bool b[100005];//判断当前点是否遍历过
void test(){//典型的bfs
point t(n,0);
a.push(t);
while(!a.empty()){
t=a.front();
a.pop();
if(t.x==k){
size=t.tmp;
return;
}else{
if((t.x+1)<=100000&&b[t.x+1]){
point t2(t.x+1,t.tmp+1);
b[t.x+1]=false;
a.push(t2);
}
if(t.x-1>=0&&b[t.x-1]){
point t2(t.x-1,t.tmp+1);
b[t.x-1]=false;
a.push(t2);
}
if((t.x*2)<=100000&&b[t.x*2]){
point t2(t.x*2,t.tmp+1);
b[t.x*2]=false;
a.push(t2);
}
}
}
}
int main(){
cin>>n>>k;
for(int i=0;i<100005;i++){
b[i]=true;
}
size=0;
test();
cout<<size<<endl;
}
上一篇: 微信小程序实现聊天对话(文本、图片)功能