第十四届华中科技大学程序设计竞赛 J 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.
#include <bits/stdc++.h>
 
using namespace std;
 
int num1(int& n)
{
    return __builtin_popcount(n);
}
const int maxn = 3e6 + 7;
bool vis[maxn];
int main()
{
    int A, B;
    scanf("%d %d", &A, &B);
    auto ck = [&] (int x)-> bool{
        if(x < 0) return 0;
        return 1;
    };
    queue<pair<int,int> > que;
    que.push(make_pair(A, 0));
    vis[A] = 0;
    while(!que.empty()) {
        pair<int,int> top = que.front(); que.pop();
        if(top.first == B) {
            return !printf("%d\n", top.second);
        }
        int nxt1 = top.first + 1;
        int nxt2 = top.first - 1;
        int nxt3 = top.first + num1(top.first);
        int nxt4 = top.first - num1(top.first);
        if(!vis[nxt1] && ck(nxt1)) {
            vis[nxt1] = 1;
            que.push(make_pair(nxt1, top.second + 1));
        }
        if(!vis[nxt2] && ck(nxt2)) {
            vis[nxt2] = 1;
            que.push(make_pair(nxt2, top.second + 1));
        }
        if(!vis[nxt3] && ck(nxt3)) {
            que.push(make_pair(nxt3, top.second + 1));
            vis[nxt3] = 1;
        }
        if(!vis[nxt4] && ck(nxt4)) {
            que.push(make_pair(nxt4, top.second + 1));
            vis[nxt4] = 1;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36876305/article/details/80151553