第十四屆華中科技大學程序設計競賽 J Various Tree【數值型一維BFS/最小步數】
阿新 • • 發佈:2018-05-01
hust there ini amp rep targe ati 數值 set
鏈接: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.
【題意】:通過4種操作n最少幾步可以達到m。
【出處】:poj 3278
#include<iostream> #include<cstring> #include<queue> using namespace std; int n,k; const int MAXN=1000010; int visited[MAXN];//判重標記,visited[i]=true表示i已經拓展過 struct step { int x;//位置 int steps;//到達x所需的步數 step(int xx,int s):x(xx),steps(s) {} }; queue<step>q;//隊列(Open表) int f(int x) { int c=0; while(x){ if(x&1) c++; x>>=1; } return c; } int main() { cin>>n>>k; memset(visited,0,sizeof(visited)); q.push(step(n,0)); visited[n]=1; while(!q.empty()) { step s=q.front(); if(s.x==k)//找到目標 { cout<<s.steps<<endl; return 0; } else { if(s.x-1>=0 && !visited[s.x-1]) { q.push(step(s.x-1,s.steps+1)); visited[s.x-1]=1; } if(s.x+1<=MAXN && !visited[s.x+1]) { q.push(step(s.x+1,s.steps+1)); visited[s.x+1]=1; } if(s.x+f(s.x)<=MAXN&&!visited[s.x+f(s.x)]) { q.push(step(s.x+f(s.x),s.steps+1)); visited[s.x+f(s.x)]=1; } if(s.x-f(s.x)>=0&&!visited[s.x-f(s.x)]) { q.push(step(s.x-f(s.x),s.steps+1)); visited[s.x-f(s.x)]=1; } q.pop(); } } return 0; }
第十四屆華中科技大學程序設計競賽 J Various Tree【數值型一維BFS/最小步數】