3278 Catch That Cow BFS入门题
2016-06-23 19:39
253 查看
Catch That Cow Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 70410 Accepted: 22143 Description Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting. * Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute * Teleporting: FJ can move from any point X to the point 2 × X in a single minute. If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it? Input Line 1: Two space-separated integers: N and K Output Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow. Sample Input 5 17 Sample Output 4 Hint The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes. Source USACO 2007 Open Silver [Submit] [Go Back] [Status] [Discuss]
#include <iostream> #include <cstring> #include <queue> using namespace std; bool Hash[400001]; //!判断该点是否走过 int main(void) { int N,K; while(cin>>N>>K) { memset(Hash,false,sizeof(Hash));//初始化Hash表 pair<int,int> p; //第一个代表横坐标,第二个代表走的步子 p.first=N;p.second=0; //初始化 Hash =true; //原点标记已走 queue< pair<int,int> > bfs; //创建队列 bfs.push(p); //把原点设为第一个队列检索项 while(!bfs.empty())//队列有元素可操作 { p=bfs.front();//获取队首 if(p.first==K) {//已经找到了该元素,输出路径长,并结束搜索 cout<<p.second<<endl; break; } p.second++; //移动次数+1 pair<int ,int> q; if(p.first<K) {//当前点在目标点的左侧 //!*2 q=p; q.first*=2; if(Hash[q.first]==false&&q.first) {//这个点没访问过,则从这点开始搜索 Hash[q.first]=true; bfs.push(q);//压入队列 } //! +1 q=p; q.first+=1; if(Hash[q.first]==false&&q.first) {//这个点没访问过,则从这点开始搜索 Hash[q.first]=true; bfs.push(q);//压入队列 } } if(p.first>0) {//任意情况下都可以通过减1步继续搜索 q=p; q.first--; if(Hash[q.first]==false) {//这个点没访问过,则从这点开始搜索 Hash[q.first]=true; bfs.push(q);//压入队列 } } bfs.pop();//队首用完出列 } } return 0; }
来源: http://poj.org/problem?id=3278
//!结构体做法 #include <iostream> #include <queue> #include <cstring> using namespace std; typedef struct {int now,step;}point; bool Hash[400001];//判断该点是否遍历过 int N,K; int Cal(void) { memset(Hash,false,sizeof(Hash)); point P;P.now = N;P.step = 0;//初始化 Hash =true; //原点标记已走 queue<point> bfs;bfs.push(P); while(!bfs.empty()) { P = bfs.front();//获取队首 if(P.now == K) return P.step; P.step ++; //步长+1 point Q; if(P.now<K) ///目标左侧 { ///+1 Q=P;Q.now++; if(!Hash[Q.now]&&Q.now){Hash[Q.now] = true; bfs.push(Q);} ///*2 Q=P;Q.now*=2; if(!Hash[Q.now]&&Q.now){Hash[Q.now] = true; bfs.push(Q);} } if(P.now>0)///任意情况都可以-1 { Q=P;Q.now--; if(!Hash[Q.now]){Hash[Q.now] = true; bfs.push(Q);} } bfs.pop();//队首用完出列 } return 0; } int main() { while(cin>>N>>K) cout<<Cal()<<endl; return 0; }