1 条题解

  • 0
    @ 2022-8-1 21:36:32

    久违的bfs

    #include<bits/stdc++.h>
    using namespace std;
    bool vis[ 100001 ] ;
    int step[ 100001 ] ;
    int n , k ;
    queue<int> q ;
    int main()
    {
        memset( step , -1 , sizeof( step ) ) ;
        ios::sync_with_stdio( 0 ) ;
        cin.tie( 0 ) ;
        cin >> n >> k ;
        q.push( n ) ;
        step[ n ] = 0 ;
        vis[ n ] = 1 ;
        while( !q.empty() ) 
        {
            int now = q.front() ;
            q.pop() ;
            if( now == k )
            {
                cout << step[ now ] ;
                break ;
            }
            if( !vis[ now + 1 ] and now + 1 < 100001 )
            {
                vis[ now + 1 ] = 1 ;
                step[ now + 1 ] = step[ now ] + 1 ;
                q.push( now + 1 ) ;
            }
            if( !vis[ now - 1 ] and now - 1 > 0 )
            {
                vis[ now - 1 ] = 1 ;
                step[ now - 1 ] = step[ now ] + 1 ;
                q.push( now - 1 ) ;
            }
            if( !vis[ now *  2 ] and now * 2 < 100001 )
            {
                vis[ now * 2 ] = 1 ;
                step[ now * 2 ] = step[ now ] + 1 ;
                q.push( now * 2 ) ;
            }
        }
        return 0;
    }
    
    • 1

    信息

    ID
    1940
    时间
    1000ms
    内存
    256MiB
    难度
    4
    标签
    (无)
    递交数
    81
    已通过
    36
    上传者