Various Tree

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.


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).

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; } 







































Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325933873&siteId=291194637