4001:抓住那头牛

4001:抓住那头牛

题目链接http://bailian.openjudge.cn/practice/4001/


#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef struct node {
    
    
	int s, bs;
	node(int ss,int bb):s(ss),bs(bb){
    
    }
};
int n, k;
int a[100100];
bool visited[100100] = {
    
     0 };
queue<node> q;
bool pd(int t) {
    
    
	return t >= 0 && t <= 100000;
}
int main() {
    
    
	cin >> n >> k;
	memset(a, 0, sizeof(a));
	q.push(node(n,0));
	visited[n] = 1;
	int flag = 0;
	while (!q.empty()) {
    
    
		node temp = q.front();
		q.pop();
		if (temp.s == k) {
    
    
			cout << temp.bs;
			flag = 1;
			break;
		}
		if (pd(temp.s-1)&&!visited[temp.s - 1]) {
    
    
			q.push(node(temp.s - 1, temp.bs + 1));
			visited[temp.s - 1] = 1;
		}
		if (pd(temp.s+1)&&!visited[temp.s + 1]) {
    
    
			q.push(node(temp.s + 1, temp.bs + 1));
			visited[temp.s + 1] = 1;
		}
		if (pd(temp.s*2)&&!visited[temp.s * 2]) {
    
    
			q.push(node(temp.s * 2, temp.bs + 1));
			visited[temp.s * 2] = 1;
		}
	}
	if (flag == 0)
		cout << 0;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46028214/article/details/114003976
今日推荐