C - Catch That Cow POJ - 3278

C - Catch That Cow POJ - 3278

首先是大暴搜+最优化剪枝(当当前搜索情况不如已有答案优时,返回)

#include<cstdio>
#include<algorithm>
using namespace std;
int n, k, ans;

int move[] = {1, -1};

void dfs(int pos, int step) {
	if(step > ans) return ;
	if(pos == k) {
		ans = min(ans, step);
		return ;
	}
	for(int i = 0; i < 3; i++) {
		if(i < 2) {
			dfs(pos+move[i], step+1);
		}
		else{
			dfs(pos*2, step+1);
		}
	}
}

int main() {
	freopen("test.in", "r", stdin);
	while(~scanf("%d%d", &n, &k)) {
		ans = abs(n-k);
		dfs(n, 0);
		printf("%d\n", ans);
	}
	return 0;
}

果然TLE了,哭哭

然后来了一发bfs

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 1e6;

int n, k, ans;

struct P {
	int pos, step;
};

void bfs(int s) {
	queue<P> Q;
	P start;
	start.pos = s; start.step = 0;
	Q.push(start);
	while(!Q.empty()) {
		P now = Q.front(); Q.pop();
		if(now.pos == k) {
			ans = now.step;
			break;
		}
		for(int i = 1; i <= 3; i++) {
			P tmp;
			tmp.step = now.step + 1;
			if(i == 1){
				tmp.pos = now.pos + 1;
			}
			else if(i == 2) {
				tmp.pos = now.pos - 1;
			}
			else {
				tmp.pos = now.pos*2;
			}
			Q.push(tmp);
		}
	}
	return ;
}

int main() {
//	freopen("test.in", "r", stdin);
	while(~scanf("%d%d", &n, &k)) {
		bfs(n);
		printf("%d\n", ans);
	}
	return 0;
}

又TLE了,呜呜呜

原来上面的bfs有很多重复的地方,比如走过的地方又走回来了,毫无意义
并且没有防止越界

AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 1e6;

int n, k, ans;
int vis[maxn];
struct P {
	int pos, step;
};

void bfs(int s) {
	queue<P> Q;
	P start;
	start.pos = s; start.step = 0;
	Q.push(start);
	while(!Q.empty()) {
		P now = Q.front(); Q.pop();
		if(now.pos == k) {
			ans = now.step;
			break;
		}
		for(int i = 1; i <= 3; i++) {
			P tmp;
			tmp.step = now.step + 1;
			if(i == 1){
				tmp.pos = now.pos + 1;
			}
			else if(i == 2) {
				tmp.pos = now.pos - 1;
			}
			else {
				tmp.pos = now.pos*2;
			}
			if(tmp.pos > 1e5 || tmp.pos < 0) continue; // 防止越界 
			if(!vis[tmp.pos]) { // 避免重复 
				vis[tmp.pos] = 1;
				Q.push(tmp);
			}
			
		}
	}
	return ;
}

int main() {
//	freopen("test.in", "r", stdin);
	while(~scanf("%d%d", &n, &k)) {
		memset(vis, 0, sizeof(vis)); 
		bfs(n);
		printf("%d\n", ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值