能想到用广搜来解这道题也够diao了:广搜到 目标节点 就可以得到答案 steps
#include<iostream> #include<queue> #include<cstring> using namespace std; struct node { int Value, Steps; node( int N, int S ): Value(N), Steps(S){} }; queue<node>Que; int Visited[100000]; int main() { int N, K; memset( Visited, 0, sizeof(Visited) ); cin>>N>>K; Que.push(node(N,0)); Visited[N] = 1; while( !Que.empty() ) { node Top = Que.front(); if( Top.Value == K ) { cout<<Top.Steps<<endl; break; } if( Top.Value-1>=0 && Visited[Top.Value-1]==0 ) { Que.push( node(Top.Value-1, Top.Steps+1) ); Visited[Top.Value-1] = 1; } if( Top.Value+1<=100000 &&Visited[Top.Value+1]==0 ) { Que.push( node(Top.Value+1, Top.Steps+1) ); Visited[Top.Value+1] = 1; } if( Top.Value*2<=100000 &&Visited[Top.Value*2]==0 ) { Que.push( node(Top.Value*2, Top.Steps+1) ); Visited[Top.Value*2] = 1; } Que.pop(); } return 0; }
时间: 2024-10-10 07:32:42