链接: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.
输入
5 12
输出
3
说明
The minimum steps they should take: 5->7->10->12. Thus the answer is 3.
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=1000000;
bool vst[maxn];
int dir[4]={1,-1};
struct State
{
int x;
int Step_Counter;
};
State a[maxn];
int BitCount2(unsigned int n) // 求二进制数中的1的个数
{
unsigned int c =0 ;
for (c =0; n; ++c)
{
n &= (n -1) ;
}
return c ;
}
bool CheckState(State s)
{
if(!vst[s.x]&&s.x>=0)
return 1;
else
return 0;
}
void bfs(State st,State ed)
{
queue <State> q;
State now,next;
st.Step_Counter=0;
q.push(st);
vst[st.x]=1;
while(!q.empty())
{
now=q.front();
dir[2]=BitCount2(now.x);
dir[3]=-BitCount2(now.x);//更改方向数组
if(now.x==ed.x)
{
cout<< now.Step_Counter<<endl;
return;
}
for(int i=0;i<4;i++)
{
next.x=now.x+dir[i];
next.Step_Counter=now.Step_Counter+1;
if(CheckState(next))
{
q.push(next);
vst[next.x]=1;
}
}
q.pop();
}
return;
}
int main()
{
State a,b;
cin>>a.x>>b.x;
bfs(a,b);
return 0;
}