I haven't done any questions for a long time...Hua Ke's questions take the bfs exam
Link: https://www.nowcoder.com/acm/contest/106/J
Source: Niuke.com
It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
1. y=x+1
2. y=x-1
3. 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.
Enter description:
One line with two integers A and B, the init type and the target type.
Output description:
You need to print a integer representing the minimum steps.
enter
5 12
output
3
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=2e6+5;
int vis[maxn];
struct node{
int weigh;
int step;
};
int f(int a)
{
int ans=0;
// cout<<a<<":";
while(a)
{
if(a&1)
ans++;a>>=1;}//cout<<ans<<endl;return ans;}int bfs(int a,int b){node p;p.weigh=a;p.step=0;vis[p.weigh]=1;queue<node>s;s.push(p);node tmp;while(!s.empty()){p=s.front();
if(p.weigh==b)
return p.step;s.pop();int x[4]={-1,1,f(p.weigh),-f(p.weigh)};for(int i=0;i<4;i++){tmp.weigh=p.weigh+x[i];if(tmp.weigh<=maxn&&tmp.weigh>=0&&vis[tmp.weigh]==0){vis[tmp.weigh]=1;tmp.step=p.step+1;s.push(tmp);}}} return -1;}int main(){int n,m;while(cin>>n>>m){//cout<<"**"<<endl;memset(vis,0,sizeof(vis));int sum=bfs(n,m);cout<<sum<<endl;}return 0; }