Various Tree(BFS)

链接:https://www.nowcoder.com/acm/contest/106/J
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

It’s universally acknowledged that there’re innumerable trees in the campus of HUST.


And there are many different types of trees in HUST, each of which has a number represent its type. The doctors of biology in HUST find 4 different ways to change the tree’s type x into a new type y:

1.    y=x+1

2.    y=x-1

3.    y=x+f(x)

4.    y=x-f(x)

The function f(x) is defined as the number of 1 in x in binary representation. For example, f(1)=1, f(2)=1, f(3)=2, f(10)=2.

Now the doctors are given a tree of the type A. The doctors want to change its type into B. Because each step will cost a huge amount of money, you need to help them figure out the minimum steps to change the type of the tree into B. 

Remember the type number should always be a natural number (0 included).

输入描述:

One line with two integers A and B, the init type and the target type.

输出描述:

You need to print a integer representing the minimum steps.

                         从a变化到b ~最短的路径是多少~bfs一下就好

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
bool vis[1500005];
struct ***
{
    int data;
    int step;
};
int erj(int x)
{
    int l=25;
    int ans=0;
    while(l>=0)
    {
        if((1<<l)&x)
        {
            ans++;
        }
        l--;
    }
    return ans;
}
int f(int x,int nu)
{
    if(nu==1)
    {
        return x+1;
    }
    else if(nu==2)
    {
        return x-1;
    }
    else if(nu==3)
    {
        return x+erj(x);
    }
    return x-erj(x);
 
}
int bfs(int st,int en)
{
    queue<***>q;
    *** sta;
    sta.data=st;sta.step=0;
    q.push(sta);
    vis[st]=1;
    while(!q.empty())
    {
        *** t=q.front();
        if(t.data==en)
        {
            return t.step;
            break;
        }
        q.pop();
        for(int s=1;s<=4;s++)
        {
            int tm=f(t.data,s);
            if(tm>=0&&tm<=1500000&&!vis[tm])
            {
                *** tem;
                tem.data=tm;tem.step=t.step+1;
                q.push(tem);
                vis[tm]=1;
            }
        }
    }
    return -1;
}
int main()
{
    int a,b;
    while(~scanf("%d%d",&a,&b))
    {
        memset(vis,0,sizeof(vis));
        int ans=bfs(a,b);
        printf("%d\n",ans);
    }
    return 0;
}


全部评论

相关推荐

10-14 23:01
已编辑
中国地质大学(武汉) Java
CUG芝士圈:虽然是网上的项目,但最好还是包装一下,然后现在大部分公司都在忙校招,十月底、十一月初会好找一些。最后,boss才沟通100家,别焦虑,我去年暑假找第一段实习的时候沟通了500➕才有面试,校友加油
点赞 评论 收藏
分享
勇敢的联想人前程似锦:如果我是你,身体素质好我会去参军,然后走士兵计划考研211只需要200多分。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务