链接:
https://www.nowcoder.com/acm/contest/106/J
来源:牛客网
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
空间限制: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.
解题思路:BFS,广度搜索,从a出发,找到b所需要的最短步数
AC代码;
#include<bits/stdc++.h> using namespace std; int a, b; int ans = 0; const int maxn = 1e6 + 4; bool fl[maxn]; struct Node { int x, step; }; queue<Node>Q; int f(int x) { int ans = 0; while (x) { if (x & 1) ans++; x >>= 1; } return ans; } int fun(int i,int x) { if (x == 0) return i - 1; if (x == 1) return i + 1; if (x == 2) return i + f(i); if (x == 3) return i - f(i); else return 0; } int main() { int flag = 0; cin >> a >> b; memset(fl, 0, sizeof(fl)); Node now; now.x = a; now.step = 0; Q.push(now); int ans = 0; if (now.x == b) { cout << now.step << endl; return 0; } while (!Q.empty()) { Node q = Q.front(); fl[q.x] = 1; Q.pop(); for (int i = 0; i < 4; i++) { int temp = fun(q.x, i); if (temp == b) { ans = q.step + 1; cout << ans << endl; return 0; } if (temp >= 0 && fl[temp] == 0) { Node next; next.x = temp; next.step = q.step + 1; fl[temp] = 1; Q.push(next); } } } cout << ans << endl; return 0; }