链接: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.
输出描述:
来源:牛客网
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.
思路:利用pair进行边搜边记录步数,bfs
代码:
#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
const int maxn=1e6+5;
typedef pair<int ,int >PII;
int x,y;
int vis[maxn];
int f[maxn];
void init()
{
int lala;
int num;
for(int i=1;i<=1000000;i++)
{
num=0;
lala=i;
while(lala!=0)
{
if(lala%2==1)
num++;
lala=lala/2;
}
f[i]=num;
}
}
/*
int f(int u)
{
int ret = 0;
while (u)
ret += (u & 1), u >>= 1;
return ret;
}
*/
int main()
{
init();
while(scanf("%d%d",&x,&y)!=EOF)
{
queue<PII>q;
q.push(PII(x,0));
// for(int i=0;i<=max(x,y);i++)
//{
// vis[i]=0;
//}
memset(vis,0,sizeof(vis));
vis[x]=1;
while(!q.empty())
{
PII p=q.front();
q.pop();
int u=p.x;
int v=p.y;
int uu;
if(u==y)
{
cout<<v<<endl;
break;
}
uu=u+1;
if(!vis[uu])
{
vis[uu]=1;
q.push(PII(uu,v+1));
}
uu=u-1;
if(!vis[uu])
{
vis[uu]=1;
q.push(PII(uu,v+1));
}
uu=u+f[u];
if(!vis[uu])
{
vis[uu]=1;
q.push(PII(uu,v+1));
}
uu=u-f[u];
if(!vis[uu])
{
vis[uu]=1;
q.push(PII(uu,v+1));
}
}
}
return 0;
}