链接:
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.
顺着思路做就好了,没有负数情况,值得学习的是二进制1的做法
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <queue> using namespace std; int f(int n) { int count = 0; while(n) { count++; //只要n不为0则其至少有一个1 n = n & (n - 1); } return count; } struct node { int x; int step; } temp; int a,b; int vis[100009]; void bfs() { int i,j,k,x,step,y; queue<node>q; temp.x=a; q.push(temp); while(!q.empty()) { temp=q.front(); q.pop(); x=temp.x; step=temp.step; //printf("x=%d step=%d\n",x,step); if(x==b) { printf("%d\n",step); return; } for(i=0; i<=3; i++) { if(i==0) { y=x+1; } else if(i==1) { y=x-1; } else if(i==2) { y=x+f(x); } else if(i==3) { y=x-f(x); } if(y>=0&&!vis[y]) { vis[y]=1; temp.x=y; temp.step=step+1; q.push(temp); } } } } int main() { scanf("%d%d",&a,&b); // printf("%d %d\n",f(a),f(b)); //printf("%d\n",bfs()); bfs(); }