POJ3278==抓住那头牛

//算法: 裸搜 (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;
}
*/ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值