codeforces two buttons

import java.util.*;

public class Main {
    static int[] vis = new int[100005];
    static int[] dis = new int[100005];

    static int n;
    static int m;


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        m = sc.nextInt();

        if (n > m) {
            System.out.printf("%d%n", n-m);
            return;
        }

        Arrays.fill(vis, 0);
        Arrays.fill(dis, 0);

        bfs();
    }

    public static void bfs() {
        Deque<Integer> que = new LinkedList<>();
        // Deque是接口,既可以做为栈,又可以作为队列,取决于调用的API

        que.offer(n);
        vis[n] = 1;
        dis[n] = 0;

        while(!que.isEmpty()) {
            int tmp = que.poll();

            if (tmp == m) {
                System.out.printf("%d%n", dis[tmp]);
                return ;
            } else {
                // n-1
                if (tmp-1 > 0 && vis[tmp-1] == 0) {
                    vis[tmp-1] = 1;
                    que.offer(tmp-1);
                    dis[tmp-1] = dis[tmp] + 1;

                }

                // n*2
                if (tmp <= m && vis[tmp*2] == 0) {
                    vis[tmp*2] = 1;
                    que.offer(tmp*2);
                    dis[tmp*2] = dis[tmp] + 1;
                }

                // n+1
                if (tmp+1 <= m && vis[tmp+1] == 0) {
                    vis[tmp+1] = 1;
                    que.push(tmp+1);
                    dis[tmp+1] = dis[tmp] + 1;
                }
            }
        }
    }
}

 

codeforces two buttons

上一篇:SMBMS②登录流程实现


下一篇:有关容斥的知识及题目解析