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;
}