3278 & [kuangbin带你飞]专题一 简单搜索 C

来源:互联网 发布:g92车锥螺纹编程实例 编辑:程序博客网 时间:2024/06/05 17:58

C - Catch That Cow

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

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<queue>using namespace std;const int maxn=1e5+5;int ans[maxn];int l,k;bool book[maxn];struct Node {    int x,num;    friend bool operator < (Node a,Node b) {        return a.num>b.num;    }};bool check(int num) {    if(num>=0&&num<=100000) return true;    return false;}int bfs() {    Node now,next;    priority_queue<Node>Q;    while(!Q.empty()) Q.pop();    now.x=l,now.num=0;    book[now.x]=false;    Q.push(now);    while(!Q.empty()) {        now=Q.top();        Q.pop();        if(now.x==k) return now.num;        next.x=now.x+1;        if(check(next.x)&&book[next.x]) {            book[next.x]=false;            next.num=now.num+1;            Q.push(next);        }        next.x-=1;        next.x=now.x-1;        if(check(next.x)&&book[next.x]) {            book[next.x]=false;            next.num=now.num+1;            Q.push(next);        }        next.x+=1;        next.x=now.x*2;        if(check(next.x)&&book[next.x]) {            book[next.x]=false;            next.num=now.num+1;            Q.push(next);        }        next.x/=2;    }    return 0;}int main(){    while(cin>>l>>k) {        memset(ans,0,sizeof(ans));        memset(book,true,sizeof(book));        cout<<bfs()<<endl;    }}
原创粉丝点击