POJ 3278 Catch That Cow
2012-06-12 16:32
204 查看
Catch That Cow
直接用bfs,由于有三种选择,+1 , -1 , *2 , 这里我们需要判断一下,有些情况下无论如何搜索都不可能获得最优解。设当前的位置为n , 牛的位置为k,那么有:
如果n > k的时候选择*2 ,与+1肯定不会得到最优解。故在这里有个剪枝。在就是当搜到的时候即退出就可以了。
直接用bfs,由于有三种选择,+1 , -1 , *2 , 这里我们需要判断一下,有些情况下无论如何搜索都不可能获得最优解。设当前的位置为n , 牛的位置为k,那么有:
如果n > k的时候选择*2 ,与+1肯定不会得到最优解。故在这里有个剪枝。在就是当搜到的时候即退出就可以了。
#include<stdio.h> #include<string.h> #define MAXN 200010 #define maxn 100000 int uset[MAXN] ; int queue[maxn] ; int front ; int rear ; void pop(){ front = (front + 1)%maxn ; } void push(int x){ queue[rear] = x ; rear = (rear + 1)%maxn ; } int first(){ return queue[front] ; } bool empty(){ if(rear==front) return 1 ; else return 0 ; } void bfs(int s, int e){ uset[s] = 0 ; push(s) ; int x ; int y ; while(!empty()){ x = first() ; pop() ; if(x == e) break ; //如果x>e,那么继续加1肯定得不到最优解 if(x < e){ y = x + 1 ; if(y==e){ uset[y] = uset[x] + 1 ; break ; } else if(uset[y] < 0){ uset[y] = uset[x] + 1 ; push(y) ; } } //不能越界 if(x >= 1){ y = x - 1 ; if(y == e){ uset[y] = uset[x] + 1 ; break ; } else if(uset[y] < 0){ uset[y] = uset[x] + 1 ; push(y) ; } } //如果x > e , 继续乘以2肯定得不到最优答案 if(x < e){ y = x * 2 ; if(y == e){ uset[y] = uset[x] + 1 ; break ; } else if(uset[y] < 0){ uset[y] = uset[x] + 1 ; push(y) ; } } } printf("%d\n" , uset[e]) ; } int main(){ int n ; int k ; scanf("%d %d" , &n , &k) ; memset(uset , -1 , sizeof(uset)) ; front = 0 ; rear = 0 ; bfs(n , k) ; return 0 ; }
相关文章推荐
- poj - 3278 Catch That Cow
- poj3278——Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278: Catch That Cow
- poj 3278 Catch That Cow bfs
- ♥POJ 3278-Catch That Cow【搜索】
- poj3278 Catch That Cow BFS
- Poj 3278 Catch That Cow
- POJ 3278 Catch That Cow (BFS)
- POJ3278——Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow(追赶母牛)
- POJ 3278 Catch That Cow
- POJ-3278 Catch That Cow
- [POJ 3278]Catch That Cow[BFS]
- POJ3278——Catch That Cow
- poj3278——Catch That Cow
- Poj 3278 Catch That Cow
- POJ - 3278 Catch That Cow
- poj 3278 Catch That Cow