POJ 3278

使用分支界限法,通常回溯法的求解目的是找出解空间中满足某约束条件的所有解,而分支界限是求出解空间的满足约束条件的一个解;  

#include<iostream> #include<queue> using namespace std; queue<int> que; int visited[100008] = {0}; int cnt[100008]; int queOut; void bfs(int here,int cow) { cnt[here] = 0; if(here == cow) return ; que.push(here); while(!que.empty()) { queOut = que.front(); que.pop(); if(queOut == cow) break; if(queOut - 1 >= 0 && !visited[queOut - 1]) { que.push(queOut - 1); visited[queOut - 1] = 1; cnt[queOut - 1] = cnt[queOut] + 1; } if(queOut + 1 <= 100000 && !visited[queOut + 1]) { que.push(queOut + 1); visited[queOut + 1] = 1; cnt[queOut + 1] = cnt[queOut] + 1; } if(queOut * 2 <= 100000 && !visited[queOut * 2]) { que.push(queOut * 2); visited[queOut * 2] = 1; cnt[queOut * 2] = cnt[queOut] + 1; } } } int main() { int start,cow; while(cin>>start && cin>>cow) { bfs(start,cow); cout<<cnt[cow]<<endl; } return 0; }

比较深度优先和广度优先两种搜索法,广度优先搜索法一般无回溯操作,即入栈和出栈的操作,所以运行速度比深度优先搜索算法法要快些。一般情况下,深度优先搜索法占内存少但速度较慢,广度优先搜索算法占内存多但速度较快,在距离和深度成正比的情况下能较快地求出最优解。因此在选择用哪种算法时,要综合考虑。

你可能感兴趣的:(算法)