第十四届华中科技大学程序设计竞赛 J Various Tree数值型一维BFS/最小步数

Posted Roni

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第十四届华中科技大学程序设计竞赛 J Various Tree数值型一维BFS/最小步数相关的知识,希望对你有一定的参考价值。

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

题目描述 
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.
示例1
输入
5 12
输出
3
说明
The minimum steps they should take: 5->7->10->12. Thus the answer is 3.

【题意】:通过4种操作n最少几步可以达到m。

【出处】:poj 3278

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

int n,k;
const int MAXN=1000010;
int visited[MAXN];//判重标记,visited[i]=true表示i已经拓展过
struct step
{
    int x;//位置
    int steps;//到达x所需的步数
    step(int xx,int s):x(xx),steps(s) {}
};
queue<step>q;//队列(Open表)

int f(int x)
{
    int c=0;
    while(x){
        if(x&1) c++;
        x>>=1;
    }
    return c;
}

int main()
{
    cin>>n>>k;
    memset(visited,0,sizeof(visited));
    q.push(step(n,0));
    visited[n]=1;
    while(!q.empty())
    {
        step s=q.front();
        if(s.x==k)//找到目标
        {
            cout<<s.steps<<endl;
            return 0;
        }
        else
        {
            if(s.x-1>=0 && !visited[s.x-1])
            {
                q.push(step(s.x-1,s.steps+1));
                visited[s.x-1]=1;
            }
            if(s.x+1<=MAXN && !visited[s.x+1])
            {
                q.push(step(s.x+1,s.steps+1));
                visited[s.x+1]=1;
            }
            if(s.x+f(s.x)<=MAXN&&!visited[s.x+f(s.x)])
            {
                q.push(step(s.x+f(s.x),s.steps+1));
                visited[s.x+f(s.x)]=1;
            }
            if(s.x-f(s.x)>=0&&!visited[s.x-f(s.x)])
            {
                q.push(step(s.x-f(s.x),s.steps+1));
                visited[s.x-f(s.x)]=1;
            }
            q.pop();
        }
    }
    return 0;
}

以上是关于第十四届华中科技大学程序设计竞赛 J Various Tree数值型一维BFS/最小步数的主要内容,如果未能解决你的问题,请参考以下文章

长春理工大学第十四届程序设计竞赛(重现赛)J.Printout

2018年湖南省第十四届大学生计算机程序设计竞赛

第十四届华中科技大学程序设计竞赛决赛同步赛

第十四届华中科技大学程序设计竞赛决赛同步赛 Beautiful Land

第十四届全国大学生智能车竞赛竞赛技术报告下载链接

第十四届华中科技大学程序设计竞赛 C Professional Manager并查集删除/虚点