码迷,mamicode.com
首页 > 其他好文 > 详细

poj3278--抓住那头牛

时间:2019-02-15 15:23:35      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:解法   star   return   line   info   题目   ant   sam   tar   

题目描述

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?

题目描述

每次牛都可以在数轴上移动,每次+1或者-1,或者是坐标*2,求最少的步数。

解法

非常非常非常地容易就可以知道这道题肯定是宽搜宽搜宽搜LJ附身,那么我们按照bfs一步一步来就可以了。

虽然有一些比较杂的优化,但是大体不变就可以A掉了。

ac代码

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
#define N 200005
using namespace std;
struct node{int x,st;};
bool vis[N];
queue<node>q;
int main(){
    int x,y;
    while(~scanf("%d%d",&x,&y)){
        while(!q.empty())q.pop();
        memset(vis,false,sizeof(vis)); vis[x]=true;
        q.push((node){x,0});
        while(!q.empty()){
            node u=q.front(); q.pop();
            if(u.x==y){printf("%d\n",u.st);break;}
            int ste=u.st+1;
            if(u.x+1<=100000&&!vis[u.x+1])q.push((node){u.x+1,ste}),vis[u.x+1]=true;
            if(u.x-1>=0&&!vis[u.x-1])q.push((node){u.x-1,ste}),vis[u.x-1]=true;
            if(u.x*2<=100000&&!vis[u.x*2])q.push((node){u.x*2,ste}),vis[u.x*2]=true;
        }
    }
    return 0;
}

poj3278--抓住那头牛

标签:解法   star   return   line   info   题目   ant   sam   tar   

原文地址:https://www.cnblogs.com/chhokmah/p/10383624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!