POJ 3278 Catch That Cow(BFS基础)
题目大意:
给你两个数字,n和k,对于n有三种变化规则。
1.n->n-1;
2.n->n+1;
3.n->2*n;
使得n==k,问如何需要最少的操作次数。
解题思路:
凡是有关最少操作次数的问题,就归结为bfs来求解,这道题是一个三入口式的bfs。。。
在搜索的过程中,一定要注意是否有需要剪纸的必要,不然蛮力上的话,必然会导致RE。
代码:
# include<cstdio> # include<iostream> # include<algorithm> # include<functional> # include<cstring> # include<string> # include<cstdlib> # include<iomanip> # include<numeric> # include<cctype> # include<cmath> # include<ctime> # include<queue> # include<stack> # include<list> # include<set> # include<map> using namespace std; const double PI=4.0*atan(1.0); typedef long long LL; typedef unsigned long long ULL; # define inf 999999999 # define MAX 100000+4 int step[MAX]; int book[MAX]; int n,k; int ans; queue<int>Q; int bfs( int n,int k ) { int next,head; step[n] = 0; book[n] = 1; Q.push(n); while ( !Q.empty() ) { head = Q.front(); Q.pop(); for ( int i = 0;i < 3;i++ ) { if ( i==0 ) next = head-1; else if ( i==1 ) next = head+1; else next = 2*head; if ( next>MAX||next<0 ) continue; if ( book[next]==0 ) { book[next] = 1; Q.push(next); step[next] = step[head]+1; } if ( next==k ) return step[next]; } } } int main(void) { while ( cin>>n>>k ) { while ( !Q.empty() ) Q.pop(); ans = 0; memset(step,0,sizeof(step)); memset(book,0,sizeof(book)); if ( n>=k ) ans = n-k; else ans = bfs(n,k); cout<<ans<<endl; } return 0; }