POJ 3278==あの牛を捕まえろ

2122 ワード

//  :    (BFS) 
#include
#include
#include
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 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  
#include
#include
#include
#include
using namespace std;
int minTime = 1 << 30;
set 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;
}
*/